I was trying to test something regarding dangling reference in c++, and came up with the following code
#include <iostream>
using namespace std;
int& get_int_ref() {
int var = 16991;
int &var_ref = var;
return var_ref;
}
int main() {
cout << get_int_ref() << endl;
return 0;
}
When I tried to compile this program with clang (clang-1000.10.44.4), I rightly got the dangling reference warning:
warning: reference to stack memory associated with local variable 'var' returned [-Wreturn-stack-address]
return var_ref;
^~~~~~~
With gcc (4.8 and 7.3.0), I didn't even get a warning. When I tried to run the executable, it prints the correct value (and not a garbage value) in all cases (with all different compilers).
$ ./a.out
16991
Clearly there is something that I am missing here. Would you agree that I shouldn't be doing this, and can someone point out what is the problem here?