Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can anyone explain the output?

Tags:

c++

function

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

like image 356
akash Avatar asked Aug 21 '12 09:08

akash


2 Answers

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.

like image 85
sharptooth Avatar answered Oct 02 '22 06:10

sharptooth


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.

like image 29
Luchian Grigore Avatar answered Oct 02 '22 08:10

Luchian Grigore