‹ BackHN Continuity

Thread

Type Punning in C and C++

36 points · 23 comments · ingve

  1. K0IN · · focus · HN ↗
    Does reinterpret_cast works in c++ for this?
    1. sheafification · · focus · HN ↗
      Yeah, you could use it for that, but it’s got some caveats and is unsafe in some cases.

      <a href="https:&#x2F;&#x2F;en.cppreference.com&#x2F;cpp&#x2F;language&#x2F;reinterpret_cast" rel="nofollow">https:&#x2F;&#x2F;en.cppreference.com&#x2F;cpp&#x2F;language&#x2F;reinterpret_cast

      EDIT: If you’re able to use C++20 then clearly bit_cast is better.

    2. jasode · · focus · HN ↗
      reinterpret_cast&lt;&gt; for punning purposes can lead to UB. The recommended C++ alternative to avoid UB is bit_cast&lt;&gt;

      <a href="https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;53401654&#x2F;why-was-stdbit-cast-added-if-reinterpret-cast-could-do-the-same" rel="nofollow">https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;53401654&#x2F;why-was-stdbit-...

    3. leni536 · · focus · HN ↗
      No.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.