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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With