Menu

📰
0

C++26: Trivial infinite loops are no longer undefined behaviour

Sandor Dargo’s Blog·18 days ago
#QDdTdUqu
Reading 0:00
15s threshold

Let’s start with a question! Is this program well-defined? 1 2 3 4 int main () { while ( true ) ; } If you said yes, you’d be wrong — at least before C++26. A while (true); loop with no side effects used to be undefined behaviour . Compilers were free to assume it terminates, and some — Clang in particular — would optimize it away entirely, with spectacular consequences : 1 2 3 4 5 6 7 8 9 10 11 // https://godbolt.org/z/WYMxxeW1T #include <iostream> int main () { while ( true ) ; } void unreachable () { std :: cout << "Hello world!" << std :: endl ; } In Clang, this prints “Hello world!” . The compiler removes the infinite loop, main falls through, and the linker-placed unreachable() function executes. This is not a compiler bug — it’s just UB, still better than nasal demons. Recently, I wrote about how C++26 reduces undefined behaviour , covering changes like erroneous behaviour for uninitialized reads and making incomplete-type deletes ill-formed. I completely forgot about this one.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More