From What happens to a declared, uninitialized variable in C? Does it have a value?, I tried playing with Ciro Santilli's code, shown below.
int f() {
int i = 13;
return i;
}
int g() {
int i;
return i;
}
int main() {
assert(f() == 13);
assert(g() == 0);
}
The call to g()
should reuse the same address of the stack frame and the value of i
in g()
, although not initialized, should be 13. I have check the address of i
in both functions and the address is the same.
However, it's 13 only when I use g++ -O0
but not with other level such as -O1
or -O3
I test this on both Windows 10 (gcc 8.1.0) and Ubuntu 18.04 (gcc 7.5.0). To be precise:
g++ -O3 -o test test.cpp -std=c++11
produce no assertion fail.
while g++ -O0 -o test test.cpp -std=c++11
gives Assertion `g() == 0' failed.
I understand that using i
in g()
falls into undefined behavior
in the standard but it seems strange to me that other optimization level seems to go out of their way to change the value of i
in g()
from 13 back to 0. Am I missing something?