← Back to context

Comment by ryao

2 days ago

There has been plenty of misinformation spread on that. One of the GCC developers told me explicitly that type punning through a union was UB in C, but defined by GCC when I asked (after I had a bug report closed due to UB). I could find the bug report if I look for it, but I would rather not do the search.

From a draft of the C23 standard, this is what it has to say about union type punning:

> 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.

In past standards, it said "trap representation" rather than "non-value representation," but in none of them did it say that union type punning was undefined behavior. If you have a PDF of any standard or draft standard, just doing a search for "type punning" should direct you to this footnote quickly.

So I'm going to say that if the GCC developer explicitly said that union type punning was undefined behavior in C, then they were wrong, because that's not what the C standard says.

  • Section J.1 _Unspecified_ behavior says

    > (11) The values of bytes that correspond to union members other than the one last stored into (6.2.6.1).

    So it's a little more constrained in the ramifications, but the outcomes may still be surprising. It's a bit unfortunate that "UB" aliases to both "Undefined behavior" and "Unspecified behavior" given they have subtly different definitions.

    From section 4 we have:

    > A program that is correct in all other aspects, operating on correct data, containing unspecified behavior shall be a correct program and act in accordance with 5.1.2.4.

Union type punning is allowed and supported by GCC: https://godbolt.org/z/vd7h6vf5q

  • I said that GCC defines type punning via unions. It is an extension to the C standard that GCC did.

    That said, using “the code compiles in godbolt” as proof that it is not relying on what the standard specifies to be UB is fallacious.

    • I am a member of the standards committee and a GCC maintainer. The C standard supports union punning. (You are right though that relying on godbolt examples can be misleading.)

https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Typ...