Possible Duplicate:
Can a local variable's memory be accessed outside its scope?!
Here is a code:
#include <iostream>
using namespace std;
double &GetSomeData()
{
double h = 46.50;
double &hRef = h;
return hRef;
}
int main()
{
double nonRef = GetSomeData();
double &ref = GetSomeData();
cout << "nonRef: " << nonRef << endl;
cout << "ref: " << ref << endl;
return 0;
}
the nonRef is printed OK as 46.5
the ref is not OK.
is the first output behavior is correct or just got lucky?
Thanks
Yes you got lucky.
Returning reference to local variable is Undefined Behavior.
Undefined Behavior means anything can happen and a behavior cannot be defined.
Regarding Undefined Behavior,
C++ Standard section 1.3.24 states: