-3

Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable's memory be accessed outside its scope?
return reference to local variable

Is it an undefined behavior when you return a ref. to a local variable ?

http://ideone.com/Kz381

int & func(){

        int x = 10;
        return x;

}

int main() {

        int &y = func();
        cout << y << endl;

}
Community
  • 1
  • 1
faressoft
  • 19,053
  • 44
  • 104
  • 146
  • 1
    I'm not sure if "local variable" has special meaning in the specification, but I imagine it would be undefined behaviour for any local variable without static storage duration. – ta.speot.is May 18 '12 at 08:28

2 Answers2

7

Yes it is. The variable is no longer available when the function ends.

You're unlucky that it appears to work. The thing is, that memory isn't cleared so the 10 is still there, but it can be reclaimed at any time, so it's definitely not safe.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5

If you want to get technical, returning it isn't undefined behavior. You only get undefined behavior when/if you try to use what was returned.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111