‹ BackHN Continuity

Thread

Type Punning in C and C++

36 points · 23 comments · ingve

  1. scoopr · · focus · HN ↗
    I just watched video[0] that argues if you can consteval something, then it must be free of UB, which seems compelling, at least for these lower level helpers.

    Unfortunately, it seems memcpy is not constexpr, so cannot be used like this, but std::bit_cast actually works[1] as constexpr, so I think in C++ that would now be the most preferred use. It won't allow the union either.

    [0] <a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=-LAXqqqX274" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=-LAXqqqX274 [1] <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;xGzjTMGvv" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;xGzjTMGvv

    1. rfgplk · · focus · HN ↗
      __builtin_memcpy is constexpr under clang with constraints
    2. leni536 · · focus · HN ↗
      Careful, only language UB is guaranteed to be detected in constant evaluation, UB in standard library functions isn&#x27;t. It is a good sanity check though.

      Also it seems that bit_cast in particular is going to be strengthened in this regard:

      <a href="https:&#x2F;&#x2F;cplusplus.github.io&#x2F;LWG&#x2F;issue4539" rel="nofollow">https:&#x2F;&#x2F;cplusplus.github.io&#x2F;LWG&#x2F;issue4539

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.