3 ms·
Assuming we're talking C, not C++, the compiler doesn't need to know that the arguments are pointers to union members, because the union members are all aligned
by boomlinde 8y ago
Assuming we're talking C, not C++, the compiler doesn't need to know that the arguments are pointers to union members, because the union members are all aligned with the union itself and have the same address. So &u.f is not some magic special pointer, it's the address of a float. So is (float *)&u. The example in the standard I think you're referring to relates to a special guarantee made about unions of structs that have a common initial sequence, that their common initial sequence can be read from either union member (AFAIK a guarantee not otherwise made about structs that share a common initial sequence).
If your func(&u.i &u.f) example fails it may be because the standard is picky about pointers of different types to the same memory. I have no idea whether it is, because I've never had to do anything like your example.
- BruiseLee 8y agoThe func can be implemented like this: float func(int *i, float *f) { *i = 42; return *f; } Since the compiler assumes that the pointers i and f do not alias, it has a right to generate the code that is equivalent to: float func(int *i, float *f) { float result = *f; *i = 42; return result; } But this will change the result of the function. So in practice if you want to do type punning using unions, the compiler must know about it.
- boomlinde 8y agoSure, by not accessing the members through the union type you lose the information the compiler needs to relax strict aliasing assumptions for union access. It's a potential footgun, but IMO only with careful aiming. It's also not strictly related to union member pointers but applies generally to aliased pointers.
- vyodaiken 8y agoThe compiler and standard are both full of contradictory, useless, and counter-productive rules on aliasing. But both gcc and clang now support _may_alias_ and -fno-strict-aliasing without which they would have made the language completely unusable.