Type-punning
Silvius Rus
rus@google.com
Fri Jun 22 10:31:00 GMT 2007
Herman Geza wrote:
> struct A {
> float x, y;
> };
>
> struct B {
> float x, y;
> };
>
> int main() {
> A a;
> B &b = reinterpret_cast<B&>(a);
> }
>
> I get a type-punned warning for this code. However, A & B is exactly the
> same type. Is the warning appropriate here?
Unfortunately gcc 4.3 will likely warn on this as well. To avoid it, we
would need a "prefix" analysis to distinguish between different structs
that are compatible up to a point. As far as I know, GCC does not have
this capability as of now. If it exists, it still needs to be connected
to -Wstrict-aliasing, which is generally not trivial, as it requires
figuring out what field is referenced where. I guess it could be
implemented in a simpler way for the special case when the structs are
identical structurally.
> Where can I find the
> definition of "almost the same [type]"?
>
C and C++ standards:
C Standard ISO/IEC 9899:1999, section 6.5, paragraph 7, and the C++
Standard ISO/IEC 14882:1998, section 3.10, paragraph 15. But there are
a couple other references that touch this.
> What is the correct way to do this:
>
> void setNaN(float &v) {
> reinterpret_cast<int&>(v) = 0x7f800001;
> }
>
> without a type-prunning warning? I cannot use the union trick here
> (memcpy works though, but it's not the most efficient solution, I
> suppose).
>
The correct and efficient solution is to use memcpy. GCC should
recognize the memcpy call and transform it into a move or load/store or
such.
You may want to try memcpy, generate the assembly code, and see if you
are happy with it.
More information about the Gcc
mailing list