Reputation: 543
Can anybody please tell me what's happening in the following code. I was expecting lvalue error and it will happen if I remove the reference return type of the function. But it's giving me output as 20. Please explain. Thanks.
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 20;
cout << fun();
return 0;
}
Upvotes: 0
Views: 108
Reputation: 3525
Basic C++ semantics:
static
variable.If you want to assign something to x
outside of fun()
, x
has to live somewhere, right? Making it static
gives it a permanent spot that will be re-accessed every time. That's why the value of 20
persists.
Upvotes: 2
Reputation: 7625
The output is as expected. In the call fun() = 20;
, the actual x
in fun()
is assigned 20
, since fun()
returns reference to x
. In the call cout<<fun();
, the assigned value is printed, which is 20
.
since x
is declared static
, it's available in memory even after func()
returns. A method scoped static
variable is created when first encounter in the method, and retains until program terminates. static
variable is initialized only once, and subsequent method call will see the last updated value. more on static
here and here.
Upvotes: 3