4 ms·
The compiler is required to successfully translate a program that contains unreachable UB, and such a program is conforming if undefined behavior is never reach
by haberman 4y ago
The compiler is required to successfully translate a program that contains unreachable UB, and such a program is conforming if undefined behavior is never reached. This is explicitly spelled out in https://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_109.html https://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_109.html
> Furthermore, if every possible execution of a given program would result in undefined behavior, the given program is not strictly conforming.
A conforming implementation must not fail to translate a strictly conforming program simply because some possible execution of that program would result in undefined behavior. Because foo might never be called, the example given must be successfully translated by a conforming implementation.
- account42 4y agoSad to see this downvoted here. 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 int * p = 0; if(fermats_last_theorem_is_wrong()) { p = malloc(sizeof(int)); *p = 0; } if(p) { puts("fermats last theorem is wrong\n"); } if(fermats_last_theorem_is_wrong()) { *p == 1; } if(p) { puts("fermats last theorem is wrong\n"); } 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.
- tsimionescu 4y agoYes, 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...