News for hackers. Stuff that matters.
Re:GCC Non-bugs by markrages on Sunday March 01, 2015 @04:02PM (#9128874)
In my embedded development, I have trained myself to use unions instead of type-punned-pointer casts to access one data type as another.

This document says this is a GCC-specific extension. Is this true? Or is it one of those things that's not standardized, but the compiler vendors all do it anyway?

Re:GCC Non-bugs by oshepherd on Sunday March 01, 2015 @06:29PM (#9129404)
Type punning by pointer is explicitly UB per the standard.

Type punning by union is implementation defined behavior. Everyone fortunately defines it to Do The Right Thing (TM).

The truly standard supported way to type pun is by memcpy

float f = ...; int x; memcpy(&x, &f, sizeof x);

Re:GCC Non-bugs by jakobegger on Monday March 02, 2015 @03:42AM (#9130944)
Yes. Use memcpy if you need to do this! This is especially important when you're on a platform that requires aligned pointers. For example, the following code will crash on ARM

    char bytes[5] = {0};
    float flt = *(float*)&(bytes[1]);
Using memcpy works on any platform with 4 byte floats:

    char bytes[5] = {0};
    float flt;
    memcpy(&flt, &(bytes[1]), 4);
Re:GCC Non-bugs by markrages on Monday March 02, 2015 @12:10PM (#9132929)
But the union won't crash either (the compiler will keep it aligned), the conversion compiles to no-op, and doesn't waste memory.

Embedded targets are always memory-constrained. If they aren't, you are wasting money on hardware.

Re:GCC Non-bugs by jakobegger on Monday March 02, 2015 @01:03PM (#9133263)
I was thinking about the case when you get unaligned data (eg you are reading from a file or from the network). Then you need to copy the data anyway.
Re:GCC Non-bugs by cremno on Sunday March 01, 2015 @05:06PM (#9129094)
It's legal C99. See DR258 / C99+TC3. But be careful, reading trap representations is UB.

http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf

Re:GCC Non-bugs by effdee on Sunday March 01, 2015 @05:08PM (#9129105)
Type-punning via unions is allowed in both C99 [0] and C11.

[0] see "ISO/IEC 9899:1999 Technical Corrigendum 3", http://www.open-std.org/Jtc1/sc22/wg14/www/docs/n1235.pdf