-7

code

#include<iostream>
using namespace std;


int &fun()
{
    int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

output wil be 10 , tell me how and when int x = 10 is changed to static int x = 10 output will be 30 .Explain both of the cases .

harshit
  • 1
  • 3

1 Answers1

4

This is undefined behavior. You are returning a reference to a local variable whose lifetime has ended at the end of the function.

It's quite amusing what g++ does with this code:

At -O0, it prints 10.

At -O1, it prints 30.

At -O2 and -O3, it prints 0.

If you declare x as static, then it has static storage duration, which means that its lifetime doesn't end when the function returns, which means that it is legal to return a reference to it. All calls to foo will return a reference to the same int.

T.C.
  • 133,968
  • 17
  • 288
  • 421