Comment by flohofwoe

Comment by flohofwoe a day ago

11 replies

> type punning in unions is undefined behavior under the C and C++ standards

Union type punning is entirely valid in C, but UB in C++ (one of the surprisingly many subtle but still fundamental differences between C and C++). There's specifically a (somewhat obscure) footnote about this in the C standard, which also has been more clarified in one of the recent C standards.

ryao a day ago

There is no footnote about it in the C standard. Someone proposed adding one to standardize the behavior, but it was never accepted. Ever since then, people keep quoting it even though it is a rejected amendment.

  • jcranmer a day ago

    Footnote 107 in C23, on page 75 in §6.5.2.3:

    > If the member used to read the contents of a union object is not the same as the member last used to store a value in the object the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called type punning). This might be a non-value representation.

    (though this footnote has been present as far back as C99, albeit with different numbers as the standard has added more text in the intervening 24 years).

    • ryao a day ago

      The GCC developers disagree with your interpretation:

      > Type punning via unions is undefined behavior in both c and c++.

      https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118141#c13

      • nialv7 2 hours ago

        I wouldn't be surprised if Andrew Pinski was just wrong. It's anecdotal but my impression of him isn't very good.

      • flohofwoe a day ago

        I'm not sure tbh what's there to 'interpret' or how a compiler developer could misread that, the wording is quite clear.