1
bool interrupted = false;
int main() {
    while (!interrupted) {
    }
}

https://godbolt.org/z/GE84EToM5

I tried it in msvc 2019 and clang (windows x64)

user1119279
  • 331
  • 3
  • 9
  • 4
    The compiler is no doubt optimizing away the 'do nothing' loop in Release Builds. Whether or not it should do that is another question, though. – Adrian Mole Aug 03 '21 at 19:57
  • 2
    Your program has undefined behavior since it has no way of exiting the loop. Both behaviors are equally "ok" (that is - your program is broken, expect anything). – Ted Lyngmo Aug 03 '21 at 19:58
  • 2
    C++ specifies you can't have an infinite loop unless it has at least one side effect from list of side effects (see [Progress guarantee](https://en.cppreference.com/w/cpp/language/memory_model#Progress_guarantee)). Your loop is infinite and does not have any of these, so it is Undefined Behavior. The compiler is allowed to assume it eventually ends. – François Andrieux Aug 03 '21 at 20:01
  • @FrançoisAndrieux brings up the progress guarantee and here's a nice example of assumptions your compiler is allowed to do: https://stackoverflow.com/a/41324327/7582247 - Edit: The duplicate question is even better. :) – Ted Lyngmo Aug 03 '21 at 20:10
  • 2
    If this is for an embedded system, you should declare `interrupted` as `volatile`. The term `volatile` means that the variable may be altered outside of the program and that the compiler should not optimize it. – Thomas Matthews Aug 03 '21 at 20:15

0 Answers0