-1

Possible Duplicate:
C++ Returning reference to local variable
Can a local variable’s memory be accessed outside its scope?

In the following code

int& h() {

int o=100;
return o; 
}

int main() {
int t=h();     //line 1
cout<<t;     //line 2
return 0;
}

Why the output is coming as 100 i.e. the value of the local variable of the function and why there is no error in line 1 because the return type of function is int& but we are returning its return value to a int.

Community
  • 1
  • 1
Luv
  • 5,381
  • 9
  • 48
  • 61

5 Answers5

7
  1. You should never return a reference or a pointer to a local variable. It will be destroyed right when the function returns. It may appear to work in some cases because the stack may not yet be overwritten. But it will fail unexpectedly eventually.

  2. It is legal to assign a reference to something to a value of the same type. So in your assignment a copy is made.

Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
4

The value is 100 because the memory containing it has just been freed and nobody has written anything to it. Here's another example:

int& h() {

    int o=100;
    return o; 
}

int& h2() 
{
    int o = 10;
    return o;
}

int main() {
    int t=h() + h2();     //line 1
    cout << t;
    return 0;
}

If you compile this with no optimization on Visual Studio, the result will be 20 and here's what will happen:

  1. h() gets called, writes 100 to memory, frees it and returns a reference.
  2. h2() gets called and writes 10 to the same place in memory (it has been freed before)
  3. main() computes the sum of 2 values from the same place in memory. Thus, it's 10+10.

Setting int from int & is not an error. It's a valid operation that means "take this reference to some object and copy whatever is there to my local variable".

Ivan Shcherbakov
  • 2,063
  • 14
  • 23
  • well done, sir. You posted basically the same thing as me, but beat me by about 30 seconds. – Daniel Jun 26 '12 at 18:37
3

Return reference local variable - for single thread application /example by Ivan/ is not problem. For multithread application is problem - when diferent threads use function e.g. h(). In this case may be moments, when threads cross used unallocate memory.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
2

Compilers don't necessarily protect against bad and/or undefined behavior.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
2

Check what options you're passing to your compiler.

Compiling your code at codepad.org produces a warning: http://codepad.org/ParI4AOG

In function 'int& h()':
Line 6: warning: reference to local variable 'o' returned
Bill
  • 14,257
  • 4
  • 43
  • 55