C++26: Trivial infinite loops are no longer undefined behaviour
a day ago
- Before C++26, a while(true); loop with no side effects was undefined behavior in C++, unlike C where such loops are well-defined.
- Compilers like Clang could optimize away the infinite loop, causing execution to fall through to subsequent code, leading to unexpected behavior such as printing 'Hello world!' from an unreachable function.
- This undefined behavior was problematic for embedded and kernel code that uses halt-on-error patterns with while(true); loops.
- C++26 fixes this with proposal P2809R3, which defines 'trivial infinite loops' as loops with an empty body and a constant true condition.
- Trivial infinite loops are now replaced with a call to std::this_thread::yield(), giving them well-defined forward-progress semantics.
- Freestanding implementations may decide whether the replacement with yield() occurs, important for bare-metal systems.