That's how it is :) The standard even describes union behavior as "type punning".
I don't know if C++ allows it though.
That's how it is :) The standard even describes union behavior as "type punning".
I don't know if C++ allows it though.
union { int i; float f; } u;
You can't safely call a function with pointers to the members like func(&u.i, &u.f), because when func was compiled, the compiler couldn't know that the arguments are pointers to union members.
This sort of thing scares me, because what the compiler can "see" isn't well defined. Is it ok if func is in the same file? Probably not. How about if I don't send the pointers to an other function and just use them locally? Probably ok, but I wouldn't trust it. If you want to type pun with a union, make sure to always access the members through the union, not with direct pointers.
The only method of type punning I 100% trust is memcpy, and if you get lucky the compiler might optimize away the overhead for you.
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.
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.