int& valueStatic()
{
staticint x = 10;
return x;
}
int& valueNonStatic()
{
int x = 10;
return x;
}
int main()
{
valueStatic() = 30; // why it works as lValue??
cout<< " value is "<<valueStatic(); // why it will print 30??
valueNonStatic() = 30;
cout<< " value is "<<valueNonStatic(); // will print 10??
}
i have executed it many times changing the value of x, output is always what we assign to x. guess this is not undefine
Executing code with undefined behavior can do anything at all, including printing what you assigned.
When I compile that program (with the missing include/using added), I get
test.cc:13:12: warning: reference to stack memory associated with local variable
'x' returned [-Wreturn-stack-address]
return x;
^
1 warning generated.
on another compiler
"test.cc", line 13.12: 1540-1103 (W) The address of a local variable or temporary is used in a return expression.
on another compiler
"test.cc", line 13: Warning: Returning a reference to a local variable or temporary.
on another compiler
test.cc: In function ‘int& valueNonStatic()’:
test.cc:12:9: warning: reference to local variable ‘x’ returned [enabled by default]
Test runs:
sun:
value is 30 value is 30
ibm:
value is 30 value is 10
but even if every compiler I have available printed 30 (or 10, or 42), it wouldn't make it any less of an error.