Undefined behavior causing time travel

There is a flow in the reasoning.

When a compiler writer says: we use Undefined Behavior to optimize a program, there are two different interpretations:

  • most people hear: we identify Undefined Behavior and decide we can do whatever we want (*)
  • the compiler writer meant: we assume Undefined Behavior does not occur

Thus, in your case:

  • dereferencing a nullptr is Undefined Behavior
  • thus executing value_or_fallback(nullptr) is Undefined Behavior
  • thus executing the else branch is Undefined Behavior
  • thus door_is_open being false is Undefined Behavior

And since Undefined Behavior does not occur (the programmer swears she will follow the terms of use), door_is_open is necessarily true and the compiler can elide the else branch.

(*) I am slightly annoyed that Raymond Chen actually formulated it this way…

Leave a Comment