4 ms·
I've been under the impression that unions don't truly allow type punning, but given that the practice was widespread (e.g., it was used in the code Protocol Bu
by maxlybbert 11y ago
I've been under the impression that unions don't truly allow type punning, but given that the practice was widespread (e.g., it was used in the code Protocol Buffers generated a few years ago), it was a pretty safe bet compilers would support it as an extension.
I was also under the impression that the One True Way to type pun was to cast to char*, which is allowed to alias, and then cast again to the type you actually want.
- asgfoi 11y agoI was also under the impression that the One True Way to type pun was to cast to char, which is allowed to alias, and then cast again to the type you actually want.* That clearly doesn't work, but I can see from a naive perspective why some think that. It feels like a nice hack, but a cast to char* doesn't "remove" the original type. To be clear: char* can alias any type, but only char* can alias char*.
- gpderetta 11y agoCasting through chard doesn't help: how do you get to a specific pointer value doesn't really matter. The C aliasing rules are only about dereferencing pointers. What is allowed, as an explicit exception to the aliasing rules, is reading an object representation by dereferencing a char pointer. This is why memcpy is the approved way to do type punning, but you do have to copy.