Type-punning

Silvius Rus rus@google.com
Wed Jun 20 00:55:00 GMT 2007


This may have been fixed by a recent patch to -Wstrict-aliasing.  Let me 
try to run the latest version of pre4.3 and will get back to you.

Herman Geza wrote:
> Hi,
>
> gcc's docs states that at -fstrict-aliasing:
>
> "In particular, an object of one type is assumed never to reside at the 
> same address as an object of a different type, unless the types are almost 
> the same."
>
> I have problems with this:
>
> 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?  Where can I find the 
> definition of "almost the same [type]"?
>
> A little more complicated example:
>
> struct A {
> 	float x, y;
> };
>
> struct B: public A {
> };
>
> struct C: public A {
> };
>
> int main() {
> 	B b;
> 	C &c = reinterpret_cast<C&>(b);
> }
>
> I get the same warning, and I even get miscompiled code with -O6 (for a 
> more complicated code, not for 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).
>
> Thanks for your help,
> Geza
>
> PS: gcc-4.1, gcc-4.2 produces this. Earlier gcc versions don't produce 
> warnings for these cases.
>   



More information about the Gcc mailing list