hn.today

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

sandordargo.com117 points143 comments
Screenshot of C++26: Trivial infinite loops are no longer undefined behaviour

Until C++26, a loop like while(true); was technically undefined behaviour: the language’s forward-progress rules allowed implementations to assume a thread will eventually terminate, perform I/O, access volatile, or synchronize, so a tight empty infinite loop could be optimized away. Compilers such as Clang exploited that freedom and removed such loops, sometimes letting execution fall through into unrelated code placed by the linker. That broke common embedded and kernel halt-on-error patterns (where a fatal failure is handled by spinning forever) and created real-world reliability and security issues. C had avoided this problem by exempting loops with constant controlling expressions, but C++ did not - until now.

C++26, via P2809R3 (also adopted as a defect resolution so implementations can backport it), defines a narrowly scoped notion of a TRIVIAL INFINITE LOOP and makes it well-defined. The loop must be a trivially empty iteration statement (body is literally ; or {}) and the controlling expression a constant expression evaluating to true. When both hold, the standard specifies replacing the loop body with a call to std::this_thread::yield(), and updates the forward-progress guarantee so the optimizer can no longer assume the loop terminates. The change lists precise examples of what qualifies and what does not, and leaves freestanding (bare-metal) implementations the option to avoid the yield replacement to preserve intended halt semantics.

Read on sandordargo.com143 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.