0

I was reading an article on references in CPP, where I found this example and couldn't understand how is that we are able to call a function and initialize a variable inside its call block. As the moment we value of the function call is returned, the function is out of the call stack all allocated memory is released.

#include <iostream>
using namespace std;
int& fun()
{
    static int x = 10;
    return x;
}
 
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

Output: 30

  • C++ must be learnt using a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of by reading random online examples. In particular, you can safely return a reference to a function static variable. – Jason Sep 20 '22 at 07:17
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. See [Returning static local variables as references](https://stackoverflow.com/questions/13424564/returning-static-local-variables-as-references) or [Returning a Static Local Reference](https://stackoverflow.com/questions/9133965/returning-a-static-local-reference) – Jason Sep 20 '22 at 07:18
  • *all allocated memory is released* That is not true of static variables like `x`. If `x` was not static you would have the problem you described, but a static variable's memory will only be released when the program exits. – john Sep 20 '22 at 07:23
  • See also: [this answer](https://stackoverflow.com/a/41831989/12002570). – Jason Sep 20 '22 at 07:24
  • A static variable is not reserving space on the call stack, but is a global variable. So the example is very artificial, just for showing that a function can return a reference. Indeed returning the reference to a local variable is a terrible error. Returning the reference to an allocated memory location could be done, but as a function has a global scope, the function's usage must be limited. So in general it is not a good idea to have such functions. – Joop Eggen Sep 20 '22 at 07:24

0 Answers0