by qznc · 13y ago · 0 comments
But only user code is required to be well-formed and have defined behavior, system headers could just as well be written in Forth as long as the actual behavior under the compiler they come with is correct.
He is not accusing the compilers of executing undefined behavior. He is accusing them of exploiting undefined behavior to "optimize" code.
His points are:
1. Current compilers will perform optimizations based on undefined behavior. That is, during the optimization phase, they will say "Aha! That's not defined! I'll instead do this much, much faster thing as an optimization."
2. Lots of real code has undefined behavior.
3. The programs that result from these codes still produce the answers we expect, mostly.
4. If we take point 1 to its logical conclusion, then point 2 means that point 3 will no longer be true. That is, if compilers aggressively and thoroughly sought out to find all instances of undefined behavior in C code, and just optimized it away, many (most?) programs would cease to do much at all.
For example, the result of x+y is undefined for signed integers in C, because we want it to compile it to a minimum number of instructions on every architecture. No instructions to check for overflow and branching afterwards. No error correction instructions on architectures where semantics differ to the language semantics.
To understand this better, realize that, ultimately, a standard is a contract. A standard says, in part, "If you refrain from doing these things, the system promises to do these things and not do these other things here."
"Undefined behavior", then, is invoked by code that strays from the standard by doing things the standard makes no guarantees about, like casting a value of type pointer-to-double to type pointer-to-char and dereferencing the result; the behavior of the compiler and the code the compiler emits is then undefined, which is to say its behavior is not guaranteed by the standard.
And, yes, a conformant C compiler is perfectly within its rights to delete code that it can tell invokes undefined behavior.