Hacker News new | ask | show | jobs
by oshepherd 4121 days ago
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);

1 comments

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

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.