Type-punning

Silvius Rus rus@google.com
Fri Jun 22 18:48:00 GMT 2007


Sergei Organov wrote:
> Herman Geza <hg211@hszk.bme.hu> writes:
>
> [...]
>   
>> 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
>>     
>
> Why? Won't the following work?
>
> void setNaN(float &v) {
>   union { float f; int i; } t;
>   t.i = 0x7f800001;
>   v = t.f;
> }
>   
As far as I know, this is guaranteed to work with GCC.  But it is not 
kosher according to language standards, so other compilers might dislike 
it.  On the other hand, other compilers are not guaranteed to optimize 
the call to "memcpy" out either.

Type punning has been disallowed regardless of disguise at least since 
Fortran77, when compiler writers realized it had become evil.  However, 
in my opinion, there's a big difference between a useful little trick 
like the union above and the horrible memory overlays that the Fortran77 
standard tried to help disambiguate.

Silvius



More information about the Gcc mailing list