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;
}
β
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.