‹ BackHN Continuity

Thread

Type Punning in C and C++

36 points · 23 comments · ingve

  1. StilesCrisis · · focus · HN ↗
    The conclusion is simply wrong. `union` should not be used for type-punning in C++, or in C code which might be compiled by a C++ compiler.

    I can't downvote posts yet, but if you have the ability, consider it. This is clearly LLM slop without human review.

    1. [deleted] · · focus · HN ↗

      [deleted]

    2. eqvinox · · focus · HN ↗
      > C code which might be compiled by a C++ compiler.

      I really hope you're talking mostly about header files; for actual code this is such a horrible idea (and in a lot of cases just won't work without massive efforts.) Even for header files, arguably one ought to really know what they're doing.

      1. StilesCrisis · · focus · HN ↗
        For sure, a union which is used as API surface to a C library which a C++ codebase uses is the most obvious and dangerous footgun here.

        The article never even discusses how C++ actually implements unions to begin with, so it's just incomplete. (Only the "active" member is meaningful, the others are considered as meaningless and shouldn't be touched.)

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.