‹ 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. echoangle · · focus · HN ↗
      The article mentions a use case for that:

      > What I found is that this is common in embedded and kernel code as a halt-on-error pattern. When a fatal error occurs and there’s no operating system to exit to, you simply stop:

      1. account42 · · focus · HN ↗
        Low level code can and should use assembly to get the precise effect they desire in these cases.
        1. mdspan · · focus · HN ↗
          That would be pretty cumbersome though. If you're targeting N different architectures, you would have to write N different assembly blocks.
        2. rcxdude · · focus · HN ↗
          I shouldn't need to drop to assembly to get an infinite loop that works!
        3. echoangle · · focus · HN ↗
          Why not just allow infinite loops instead of having me write assembly for it though?
          1. account42 · · focus · HN ↗
            Because a compiler being allowed to assume that a loop always terminates gives it more room to optimize the 99% of loops that aren't supposed to run until the heat death of the universe.
            1. echoangle · · focus · HN ↗
              Or you could just detect while loops with constant condition (like the C standard) and not touch any programs that don't exhibit UB while allowing infinite loops for other use cases at zero runtime cost and negligible compile cost.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.