union {
int i;
float f;
} *u;
float f = 3.14;
u = &f;
x = u->i;
> In this case the memory pointed to by “u” has the declared effective type of int, and given that “u” is a union that contains int, the access using the “i” member is legal. It’s noteworthy in this that the “f” member of the union is never used, but only there to satisfy the requirement of having a member with a type compatible with the effective type.Is this a typo? Should it say "declared effective type of float" and "“u” is a union that contains float"?
It's interesting to see type-punning using a union - I've read that it should be avoided and to use `memcpy` instead. Are there any issues with the union approach in C? Or is the advice to prefer `memcpy` specific to C++, where AFAICT the union approach is undefined behaviour?
cancerhacker•3h ago
It seems like a lost art to think that way. It’s disturbing to me how many candidates couldn’t write Hello World and compile it from the command line.
Everyone should spend some time with godbolt.org or better, the -save-temps compiler flag, to see how changes affect your generated code. Right now. I’ll wait. (Shakes cane at kids)
anyfoo•3h ago
But it's rough, and dangerous. Optimizers do a lot these days, and I really mean a lot. Besides completely mangling your program order, which includes shoving entire blocks of code into places that you might not have guessed, they also do such things as leveraging undefined behavior for optimizations (what the article is partly about), or replacing entire bits of code by function calls. (A compiler might make code out of your memcpy(), and vice versa; the latter can be especially surprising.)
If you care about the assembly representation of your C code (which kernel developers often do), you will spend a lot of time with the "volatile" keyword, compiler barriers, and some obscure "__attribute__"s.
But I agree, even with those caveats in mind, it's a very useful skill to imagine your C code as what it translates to (even if that representation is just a simplified model of what the compiler will actually do).
lalaithion•1h ago