home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,174 of 33,346   
   SG to All   
   Re: Aliasing problem wit reinterpret_cas   
   23 Aug 13 21:42:40   
   
   From: sgesemann@googlemail.invalid   
      
   Am 23.08.2013 22:11, schrieb peter koch larsen:   
   >     [...]   
   >     unsigned frac = fraction;   
   >     [...]   
   >     float res = reinterpret_cast(frac);   
   >   
   > [...] The code compiled and   
   > worked fine using Microsoft Visual C++, but when compiled with gcc 4.1.2   
   > using O2, the code returned values, that were completely unrelated to   
   > what was actually stored.   
   >   
   > Replacing the last two lines with   
   >   
   >     return (exp_sign & 0x80) ? -reinterpret_castfrac)   
   >                              :  reinterpret_cast(frac);   
   >   
   > Made the program work as as expected.   
   > My question for those of you that have followed me so far is whether   
   > this is a gcc-bug or it is simply a lacking understand of C++.   
      
   You are invoking undefined behaviour.   
   It's a violation of the strict aliasing rule.   
   In C++03 it was §3.10/15.   
   But the numbering probably changed with C++11.   
      
   Use   
      
       float res;   
       static_assert(sizeof res == sizeof frac,"float/int issue");   
       memcpy(&res,&frac,sizeof res);   
      
   instead. GCC also supports type punning via a union as an extension.   
   Keep in mind that this union trick is an extension and not guaranteed to   
   work by the C++ ISO standard. But the use of memcpy is as portable as   
   you can get in this case. GCC is aware of what memcpy does (intrinsic   
   function). It does exactly what you want without any overhead.   
      
   Cheers!   
   sg   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca