Can anyone explain the output?
#include<iostream>
using namespace std;
int &fun(){
static int x = 10;
return x;
}
int main(){
fun() = 30;
cout << fun();
return 0;
}
output is 30
That's how static locals work - they persist the value between the function calls. Basically fun()
has a static local and returns a reference to it, the effect is roughly the same as you would have with a global variable.
You return the static by reference, so when you do fun() = 30
you change it.
It's pretty clear, no?
Basically, foo()
returns a reference to x
.
When you call fun()
a static variable is created and you return the reference to it. Basically, because of the static
, the variable is not destroyed even if you exit the scope of the function. You affect the reference with 30 and then recalling the function you get 30 (the x at the second call is exactly the same at the first call). Basically the static works like a global variable in this case.
AS fun is the reference to the function so when you write this line fun() = 30;
it stores 30 in its return value ie x
, that is why you are getting the output as 30.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.