c++ - return reference to local variable -
c++ - return reference to local variable -
possible duplicate: can local variable's memory accessed outside scope?!
here code:
#include <iostream> using namespace std; double &getsomedata() { double h = 46.50; double &href = h; homecoming href; } int main() { double nonref = getsomedata(); double &ref = getsomedata(); cout << "nonref: " << nonref << endl; cout << "ref: " << ref << endl; homecoming 0; } the nonref printed ok 46.5 ref not ok.
is first output behavior right or got lucky?
thanks
yes got lucky.
returning reference local variable undefined behavior. undefined behavior means can happen , behavior cannot defined.
regarding undefined behavior,
c++ standard section 1.3.24 states:
permissible undefined behavior ranges ignoring situation unpredictable results, behaving during translation or programme execution in documented manner characteristic of environment (with or without issuance of diagnostic message), terminating translation or execution (with issuance of diagnostic message).
c++ compiler-construction pass-by-reference
Comments
Post a Comment