πŸ“Š C++
Q. What is the output of the following C++ program?
Code:
#include<iostream> 
using namespace std;
int &f() {
  static int x = 10;
  return x;
}

int main() {
  int &y = f();
  y = y +5;
  cout << f();
  return 0;
}
  • (A) 10
  • (B) 5
  • (C) 15
  • (D) Compilation error
πŸ’¬ Discuss
βœ… Correct Answer: (C) 15

Explanation: The program works correctly because ‘x’ is static. Since ‘x’ is a static variable, its location in memory remains valid even after f() returns. Thus, we can return a reference of a static variable.

Explanation by: Dharmendra Sir
The program works correctly because ‘x’ is static. Since ‘x’ is a static variable, its location in memory remains valid even after f() returns. Thus, we can return a reference of a static variable.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
200
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Dharmendra Sir
Publisher
πŸ“ˆ
94%
Success Rate