From: erik.alapaa@bredband.net   
      
   Den tisdagen den 30:e oktober 2012 kl. 20:37:15 UTC+1 skrev Martin   
   Bonner:   
   > Just because the address is the same, doesn't mean you are allowed   
   > to break the rules about using the right members. Consider the   
   > following code.   
   > #include    
   > int main() {   
   > union { int i; float f } x;   
   > float *pf = &x.f;   
   > x.i = 1;   
   > *pf = 2.0;   
   > printf( "2.0 as int == %d\n", x.i );   
   > return 0;   
   > }   
   >   
   > This code invokes undefined behaviour by using x.i when x.f was the   
   > last member to be written. An optimizing compiler may well optimize   
      
   I thought that the standards (both C and C++) explicitly allowed   
   writing to one union member, and then reading from another. For   
   example, from ISO/IEC 9899:TC2:   
      
   'An object shall have its stored value accessed only by an lvalue   
   expression that has one of the following types:   
      
   an aggregate or union type that includes one of the aforementioned   
   types among its members (including, recursively, a member of a   
   subaggregate or contained union), or' <...>   
      
   So, swapping the low and high 16-bit parts of a 32-bit word could be   
   done, fully standards-compliant, portable and no UB, by the (C) code   
   below. Correct or not?   
   (As a sidenote, similar code, without using a union, seems to work   
   well with gcc on x86 and x86_64, but not with gcc on modern RISC   
   processors. Without the union, gcc gives strict aliasing warnings on   
   RISC CPUs, as expected.)   
      
   typedef union   
   {   
    uint32_t u32;   
    uint16_t u16[2];   
   } U32;   
   uint32_t   
   swap_words(uint32_t arg)   
   {   
    U32 in;   
    uint16_t lo;   
    uint16_t hi;   
      
    in.u32 = arg;   
    hi = in.u16[0];   
    lo = in.u16[1];   
    in.u16[0] = lo;   
    in.u16[1] = hi;   
      
    return (in.u32);   
   }   
      
   Regards,   
      
   /Erik Alapää   
      
      
   --   
    [ 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)   
|