0

I am baffled how come the following program works fine. I am returning a reference to local variable from a function and a reference is assigned a value more than once. I would expect compiler to throw an error for 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;
}
polapts
  • 5,493
  • 10
  • 37
  • 49
  • 7
    It is just *undefined behaviour*. – juanchopanza Apr 08 '14 at 15:30
  • It works cause you're lucky. – Ivan Apr 08 '14 at 15:31
  • It is working, but probably not correctly. It is interpreting that address as an `int`, but anything may be there after you leave the function and `myNum` falls out of scope. – Cory Kramer Apr 08 '14 at 15:31
  • @IvanGrynko **un** lucky! The best you can hope for with UB is a very noisy crash letting you know you've done something badly wrong. If it appears to work, it'll bite you in the bum later. – BoBTFish Apr 08 '14 at 15:32
  • It is possible for undefined behavior to produce the *right* behavior – yizzlez Apr 08 '14 at 15:32
  • See http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – jcoder Apr 08 '14 at 15:34
  • Compile with all warnings and the compiler should **warn** you that you return the address of a local variable. – Jabberwocky Apr 08 '14 at 15:36

1 Answers1

1

That is undefined behavior. As per §1.3.24, undefined behavior is described as:

behavior for which this International Standard imposes no requirements

Contrary to popular belief this doesn't mean it will always produce an error. The standard just imposes no requirements whatsoever.


Why did it allow "Value1 = getNum(); ". Value1 is a reference, already assigned to something.

Because in:

Value1 = getNum();

you are not reassigning a reference. You are calling operator= on an int which copied the value of the returned value of getNum to Value1.

Shoe
  • 74,840
  • 36
  • 166
  • 272