For instance, consider the following:
int main(void) {
int K;
int Y;
printf("%d", K==Y);
return 0;
}
Is it possible for the output to ever be a 1
?
For instance, consider the following:
int main(void) {
int K;
int Y;
printf("%d", K==Y);
return 0;
}
Is it possible for the output to ever be a 1
?
The result of reading the value of an uninitialized variable is undefined, meaning that anything could happen. I would say it's possible for the output to be a 1.
The thing here is that both variables K
and Y
have automatic storage duration, and its address is never taken - it could have been declared with register
storage class, C11 6.3.2.1p2 says that
If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
Because the behaviour is undefined anything might happen. In practice this rule exists because there are computer architectures where the processor registers would be set to "unset" upon an entry to a function - accessing such a register would actually trigger a hardware trap that will cause the program to crash.
This rule has then lead to other compilers doing all sorts of wild stuff with these - it might be that no register will be allocated for a variable before it is assigned to, so you might see the value of the variable changing over executions, so it might be that consecutive invocations
printf("%d", K==Y);
printf("%d", K==Y);
might print different values.
Reading uninitialized local variables with automatic storage has undefined behavior. Anything can happen:
1
0
Hello world