c++ - Why does the following program works fine? I am returning a reference to local variable from a function -
this question has answer here:
i baffled how come following program works fine. returning reference local variable function , reference assigned value more once. expect compiler throw error reference assignment.
#include <iostream> using namespace std; int& getnum() { int mynum = 89; return mynum; } int& getanothernum() { int mynum = 1000; return mynum; } int main() { int& value1 = getanothernum(); cout << "value1 value is: " << value1 << endl; value1 = getnum(); cout << "value1 value is: " << value1 << endl; return 0; }
that undefined behavior. per §1.3.24, undefined behavior described as:
behavior international standard imposes no requirements
contrary popular belief doesn't mean produce error. standard imposes no requirements whatsoever.
why did allow "value1 = getnum(); ". value1 reference, assigned something.
because in:
value1 = getnum();
you not reassigning reference. calling operator=
on int
copied value of returned value of getnum
value1
.
Comments
Post a Comment