Re:Falsehoods programmers believe about undefined behavior
by tsimionescu on Tuesday November 29, 2022 @03:33AM
(#33785053)
Yes, my example with Fermat's last theorem was completely wrong, not sure why it seemed plausible to me when I wrote it, it's obviously just a guard, and it obviously is not UB to have a pointer write behind an If...
To hammer it in, the consider the following:
if(p) *p = 0;
*p is undefined if p is NULL. But as long as that statement is never reached when p is NULL that is not a problem. That is trivially true in this case, but the same applies even for more complex relations between the conditional and the undefinedness of the statement.
Or put another way, in
the compiler is not allowed to remove the if(p) checks and unconditionally print that fermats last theorem is wrong unless it can prove that fermats_last_theorem_is_wrong() is true.In fact, something having undefined behavior and the compiler being allowed to assume that it is unreachable are effectively the same thing. Which is why the spec for std::unreachable() and the compiler-specific intrinsics that preceded it is that it invokes undefined behavior and not more complex wording.