Reputation: 877
Consider the following code snippet in C++:
#include <iostream>
using namespace std;
int &fun()
{
static int a = 10;
return a;
}
int main(int argc, char const *argv[])
{
int &y = fun();
y += 30;
cout << fun();
return 0;
}
Output: 40
How is output of the code snippet given above justified?
Upvotes: 1
Views: 108
Reputation: 303517
fun
isn't a function pointer, it's a nullary function that returns an int&
. Specifically, it returns a reference to a static int
named a
.
So what your program does is:
int &y = fun(); // this is the first call to fun, so we initialize a.
// it now has a value of 10, and we return a reference to it
// so y is a reference to the static variable local to fun()
y += 30; // y == 40
// since y is a reference to "fun::a", a is now 40 too
cout << fun(); // a is static, so it will only get initialized once.
// that first line is effectively a NOOP, so fun() just
// returns a reference to it. which has a value of 40.
Upvotes: 2
Reputation: 15868
You are not using function pointers, but just storing the result of a call to fun
in a reference.
a
is static variable, and you are initialising a reference to that variable. A reference is just another name for a
, in this case, so that's why modifying the value of the reference y
, you modify also the value a
, which is static, that means that its value is preserved from call to call.
Upvotes: 2