‹ BackHN Continuity

Thread

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

173 points · 290 comments · ibobev

  1. account42 · · focus · HN ↗
    Unfortunate. There isn't ever a good reason to have an infinite loop so concerned compilers could have just diagnosed this as a warning.
    1. weinzierl · · focus · HN ↗
      For Rust the infinite loop is important enough to have its own keyword.
      1. kibwen · · focus · HN ↗
        The reason for this is interesting. Loop constructs that you're guaranteed to enter have implications for control flow (in every language, not just Rust). It means that the following program is valid in Rust:

            let x; // declared, but uninitialized variable
            loop { // control flow is guaranteed to enter this loop
                if some_condition() {
                    x = 42; // initialize x
                    break;
                }
            }
            foo(x); // Rust knows that x is initialized as of here in all possible paths
        
        In contrast, while loops check their condition before entering, which means the entire loop body might be skipped. Languages which guarantee initialization-before-use might special-case certain conditions for while loops as a hint to the control flow analysis (e.g. Java special-cases `while(true)`), but obviously this doesn't generalize to arbitrary conditions.

        Interestingly, this all suggest that, in C-like languages, the more natural implementation of an infinite loop should not be `while(true)` nor `for(;;)`, but rather `do {} while(true)`, because do-while are also guaranteed to enter their body (and note that Rust doesn't feature do-while loops).

        1. tialaramex · · focus · HN ↗
          Ooh, that's elegant, thanks for sharing
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.