0

test1 is correct(compiling with g++), but test2 is error. Why?

int& test1(){
    int a = 10;
    int& res = a;
    return res;
}
int& test2(){
    int a = 10;
    return a;
}
xinger
  • 43
  • 5
  • 7
    [Both are not good.](https://wandbox.org/permlink/86twjI5yKAxkemwO) – MikeCAT Apr 21 '21 at 10:26
  • 2
    Both are invalid, you return a reference to object that is dead. – Yksisarvinen Apr 21 '21 at 10:26
  • 1
    you can but you shall not. – 463035818_is_not_an_ai Apr 21 '21 at 10:27
  • local variables cease to exist once the function returns, you can return the reference but it is completely useless outside of the function – 463035818_is_not_an_ai Apr 21 '21 at 10:29
  • Coz variable a is local and you can't access it in the function. But if you declare it as global you can access it inside. – alphaX64 Apr 21 '21 at 10:31
  • [Here](https://wandbox.org/permlink/rawZ46r42JjCgWF3) is a reason you shouldn't do `test1`. [Here](https://wandbox.org/permlink/1F1PGFM2tCFSpTl8) is a reason you shouldn't do `test2`. Both codes cause undefined behavior. Anything can happen. The first exampe returns unexpected values and the second example crashes. It's probably even possible to make `test1` crash, too. –  Apr 21 '21 at 10:31
  • _"Why?"_ Because: https://stackoverflow.com/questions/7499864/returning-reference-to-a-local-variable –  Apr 21 '21 at 10:36
  • it is correct when compiling test1 with gcc – xinger Apr 21 '21 at 10:53
  • @xinger Compilers can't catch every variation of every error that exists... your first example makes it harder to catch because of the intermediate assignment, but returning a reference or pointer to a local is a very bad idea no matter how you do it. – dandan78 Apr 21 '21 at 10:59
  • see here for an example where `test1()` fails miserably: https://godbolt.org/z/nGa96eYnc Look at the output, then turn on compiler optimizations via -O2, look at the output again. Thats one typical consequence of undefined behavior. Only with optimizations turned on the compiler cares to optimize away code thats not doing any good anyhow – 463035818_is_not_an_ai Apr 21 '21 at 11:26
  • interestingly gcc only issues a warning when optimizations are turned on. – 463035818_is_not_an_ai Apr 21 '21 at 11:28
  • Voting to reopen because many people will fail to find the duplicate question - the question titles are expressed in very different ways. – Tim Cooper Apr 25 '21 at 21:51

0 Answers0