Using:
g++ -Wall -ansi foo.cpp
I get the warning
foo.cpp:31: warning: reference to local variable ‘x’ returned
from the function :
int &bar(int x) {
return x;
}
but, removing that function from the file, I get no warning from the following function:
int &get_max(int x, int y) {
return x > y ? x : y;
}
Why does the compiler allow this?
It looks like a bug, the warning is inconsistent, if we turn on optimization in gcc 5.1 it does catch this case:
warning: function may return address of local variable [-Wreturn-local-addr]
return x > y ? x : y;
^
while without optimization gcc misses it.
So the best thing to do would be to file a bug report. If they don't believe it is a bug or won't fix it then at least there will be a reference for others having the same issue.