Search code examples
c++pass-by-reference

return reference to local variable


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?


Solution

  • 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:

    Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).