I have written a little program:
#include <stdio.h>
void tester() {
int x = 69;
}
void x() {
int x;
printf("%d\n", x);
}
int main() {
tester();
x();
}
which I expect to print out 69. It prints out 69 when I compile without optimization, but with O1-O3, it prints out large numbers. Why is this?
CodePudding user response:
Attempting to read an uninitialized variable that never had its address taken triggers undefined behavior, which basically means that the program is not required to behave in any particular way.
It's clear that you were attempting to have the uninitialized variable x
in the function x
to get the "left over" value of x
in tester
. With optimization disabled this is how it happens to work. With optimization enabled, the compiler takes advantage of undefined behavior to assume it does not happen and make certain optimizations based on that fact.
So with optimization enabled, the compiler is basically assuming you won't read an uninialized variable which is why you see different output.
CodePudding user response:
those 2 x variable are totally different things, they just happen to have the same name. If you want it to be the same x then you must create a global variable
int x;
void tester() {
x = 69;
}
void xx() {
printf("%d\n", x);
}
int main() {
tester();
xx();
}