0

Since 10.1, given this code:

extern int flag;
extern "C"
void wait() {
    while(flag);
}
int flag = 4;

g++ returns this assembly

wait:
        ret
flag:
        .long   4

Clang does it too! Why is this allowed? It seems clearly wrong.

Here it is on godbolt: https://godbolt.org/z/qeWGMGa87

MemoryWrangler
  • 335
  • 2
  • 10
  • Why wouldn't it? It's not `atomic` or even `volatile`. Well that explains hoisting the load, to make `if(flag) while(1){}` ([MCU programming - C++ O2 optimization breaks while loop](https://electronics.stackexchange.com/a/387478)). But to optimize away that, too, infinite loops with no side effects or volatile accesses are UB in C++, so it can assume it terminates. – Peter Cordes Nov 08 '22 at 06:52
  • 1
    An infinite loop that has no observable behaviour gives undefined behaviour in C++. An implementation can do anything it likes, including hanging the program, consuming all CPU resources, giving a diagnostic, not giving a diagnostic, electrocuting the programmer (rare in practice, otherwise the number of programmers would be seriously less than it is), or (as is happening in your case) optimising it away. – Peter Nov 08 '22 at 06:56

0 Answers0