returning by reference from function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;
 
int &fun()
{
    int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

The code outputs 10.

Shouldn't it show an error because x is created locally on stack and gets destroyed on function return?
The behavior is undefined, anything can happen, including the output of 10.

For more detail, see this famous stackoverflow answer: http://stackoverflow.com/a/6445794/273767
Topic archived. No new replies allowed.