‹ BackHN Continuity

Thread

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

173 points · 290 comments · ibobev

  1. Aurornis · · focus · HN ↗
    I never would have guessed that the unreachable() function would get executed in that example. Probably not something you’d encounter in practice, though I have seen some weird things happen with layers of #ifdef
    1. mathisfun123 · · focus · HN ↗
      > Probably not something you’d encounter in practice

      it's actually probably the most common footgun you'll encounter in practice: non-void functions with no return statements just keep executing past their end. ask me how i know.

      compile with -Wreturn-type if you want to avoid such things...

      1. mitxela · · focus · HN ↗
        In C. In C++ it's an error to not return, as it should be.
        1. mathisfun123 · · focus · HN ↗
          .... The blog post literally demonstrates that it is not. Feel free to repro on your own machine.
          1. mitxela · · focus · HN ↗
            The main function in the blog post returns at the end of all control paths. Firstly because main has an implicit "return 0" at the end and secondly because no control paths end. It doesn't jump to unreachable because it lacks a return - it jumps there because that's how this implementation has chosen to compile UB, despite the presence of all necessary returns.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.