Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return reference to local variable [duplicate]

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?

like image 863
sramij Avatar asked May 10 '26 17:05

sramij


1 Answers

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).

like image 174
Alok Save Avatar answered May 13 '26 08:05

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!