5 ms·
Your code is int x; if(x == 0) foo(); if(x != 0) foo(); That is reading the uninitialized value twice. Since it is unspecified, it does not have t
by tspiteri 7y ago
Your code is
int x;
if(x == 0) foo();
if(x != 0) foo();
That is reading the uninitialized value twice. Since it is unspecified, it does not have to be consistent, so you could get the same behavior as non-zero for the first reading, and zero for the second reading. Changing your code to:
int x;
if(x == 0) foo();
else foo();
will give different output (same if you use !=).
- ncmncm 7y agoA good optimizing compiler will just elide the whole code block.
- tspiteri 7y agoOnly if there was UB, and the point is that there probably isn't. (I'm not really knowledgeable on the C standard, so I might have misinterpreted something.)
- ncmncm 7y agoMaking an "if" statement depend on the value of the uninitialized memory is an example of what is meant by using the value, and thus UB. In the compiler discovers UB, the Standard places no requirements of any kind on the program or compiler. It is free to launch missiles, or (more likely) assume this code cannot be reached, and omit it from the program, along with any code that reaches it unconditionally, and any check that would send control that way. Such elision is the basis for many important optimizations. Implementations are free to define things left undefined by Standards. For example, "#include <unistd.h>" is UB by the ISO Standard, but defined by Posix, which implementations also adhere to.
- comex 7y agoIndeed, but in fact there is UB: https://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior https://stackoverflow.com/questions/11962457/why-is-using-an...
- lmm 7y agoUnspecified values are constant (since they are values), just unspecified. This behaviour is only permitted because reading uninitialised memory is UB; you won't see the same thing if x is an unspecified value.