A

Admin • 833K Points
Coach

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
  • Correct Answer - Option(C)
  • Views: 20
  • Filed under category C++
  • Hashtags:

Explanation by: Admin

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.

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.