3 ms·
[Edit: this isn't true] That is definitely how it is used, and it works on the major compilers. But, surprisingly, this is indeed undefined behaviour according
by quietbritishjim 6y ago
[Edit: this isn't true] That is definitely how it is used, and it works on the major compilers. But, surprisingly, this is indeed undefined behaviour according to the standard. There was an infamous rant by Linus [1] (more infamous for the language than the subject) about how the kernel can and should continue to use unions for type punning. He noted that even though the C standard doesn't specify a behaviour for that usage, gcc does (so long as you don't use a particular compiler switch mentioned in that discussion), and went on to say "The standard simply is not important, when it is in direct conflict with reality and reliable code generation."
EDIT: Having looked into this more I think I was getting confused with C++ (where the only supported way to type pun is to use memcpy or similar, which despite the name might not have to actually copy the bytes at runtime). Here [2] is a StackOverflow answer (/discussion) on the matter.
[1] https://www.yodaiken.com/2018/06/07/torvalds-on-aliasing/ https://www.yodaiken.com/2018/06/07/torvalds-on-aliasing/
[2] https://stackoverflow.com/questions/25664848/unions-and-type-punning https://stackoverflow.com/questions/25664848/unions-and-type...
- pansa2 6y ago> The standard simply is not important Does the Linux kernel still only support compilation using gcc? That’s about the only situation in which the standard could be considered “not important”. I wonder how many other C projects are in the same situation and only support the use of a single compiler?
- saagarjha 6y agoGoogle builds Linux using Clang for Android and Chrome OS.
- quietbritishjim 6y ago> Does the Linux kernel still only support compilation using gcc? There was an effort to build the kernel with Clang [1], I'm not sure about its current status. It helps that Clang tracks GCC's features quite closely, including some of its idiosyncracies. [1] https://lwn.net/Articles/734071/ https://lwn.net/Articles/734071/
- deleted 6y ago[deleted]
- saagarjha 6y agoNo, the C standard defines it as I had specified: > 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 trap representation. This verbiage has existed in a footnote of the standard since a defect report was filed against C99: http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm. This happens to be one of the few instances where Linus is right about the C standard, but without knowing why ;)
- quietbritishjim 6y agoYep, you're right, my mistake