News for hackers. Stuff that matters.
Re:Wrong optimization with aliasing by maxlybbert on Monday February 15, 2016 @09:35PM (#11107558)
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.

Re:Wrong optimization with aliasing by asgfoi on Tuesday February 16, 2016 @03:00AM (#11108476)
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.*

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

Re:Wrong optimization with aliasing by gpderetta on Tuesday February 16, 2016 @05:59AM (#11109077)
Casting 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.