0

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;
}
sarath
  • 513
  • 6
  • 18
  • Which part don't you understand? – juanchopanza May 20 '14 at 14:11
  • Don't forget the fact that `x` is static. – 101010 May 20 '14 at 14:11
  • 2
    Probably made `x` static to get rid of a compiler warning about returning a reference to non-static local variable... – Jeff May 20 '14 at 14:12
  • You don't get error because `x` is declared as having static linkage. As such even if the scope of `fun` exits `x` resides in a special implementation defined memory. check this SO question out http://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-c – 101010 May 20 '14 at 14:15
  • @Sarath what exactly are you trying to accomplish, btw? – Jeff May 20 '14 at 14:21
  • This is actually a variant of a very common idiom, used to access class member variables and items in containers. It's what makes `operator[]()` work the way you expect. – Rob K May 20 '14 at 14:30
  • @40two Actually, `x` has *no linkage*, not static linkage (there's no such thing). What's static about `x` is its lifetime. – ach May 20 '14 at 14:52

2 Answers2

3

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.

Rakib
  • 7,435
  • 7
  • 29
  • 45
2

Basic C++ semantics:

  • You can't assign to the return values of functions unless the return type is a reference.
  • A function can't return a reference to a local variable unless it's a static variable.
  • Static variables' values persist between accesses.

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.

Jeff
  • 3,475
  • 4
  • 26
  • 35