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 32,621 of 33,346   
   Martin Bonner to James K. Lowden   
   Re: Strict aliasing and marshalling   
   30 Oct 12 12:37:08   
   
   From: martinfrompi@yahoo.co.uk   
      
   On Monday, October 29, 2012 8:26:08 PM UTC, James K. Lowden wrote:   
   > Am I reading the C++11 standard too strictly?   
   No.   
      
   > 9.5 also says,   
   >  "In a union, at most one of the non-static data members can be   
   >   active at any time, that is, the value of at most one of the   
   >   non-static data members can be stored in a union at any time."   
   >   
   > On one hand, the standard assures us the elements in a union all   
   > have the same starting address.  On the other hand, it says only one   
   > can be active at a time, which tells me I can't read a member unless   
   > that member is the one most recently written to.   
      
   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   
   the whole thing to:   
      printf( "2.0 as int == %d\n", 1 );   
   because it knows that nothing has altered x.i since it was written.   
      
      
   --   
         [ 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