That's the way I think it _should_ work, but sadly does not.
For instance, see https://godbolt.org/z/ent-xp
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 !=).https://stackoverflow.com/questions/11962457/why-is-using-an...
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.