Email: Password: Remember Me | Create Account (Free)

Back to Subject List

Old thread has been locked -- no new posts accepted in this thread
???
08/27/08 00:00
Read: times


 
#157782 - Not hiding cast
Responding to: ???'s previous message
Yes, the text in the language standard quite clearly indicates that the union was not intended as a way to hide typecasts between different data types.

The reason why it does work to use a union, is that the address of all members of a union must be the same as the address of the union - and the align and size of the union must correspond to the hardest align/size requirements of any member. M$ has spent a lot of time spreading the custom of using unions for type casting. Their help files warmly recommends using a union/struct combination to glue togeter two 32-bit integers into a 64-bit integer.

The use of a union to perform a typecast will work as long as the two members have identical size.

But what I don't like, is that it hides the typecast. A reader of the code may not realize it, resulting in a lot of grief. When you see an explicit type cast, you always know that it is based on one or more assumptions, and that a bit of care is needed when modifying the code.

If using C++, I recommend the new-style casts since they are easier to search for in the code.

List of 10 messages in thread
TopicAuthorDate
silly C question            01/01/70 00:00      
   *(float*)&time            01/01/70 00:00      
      Thanks!!!            01/01/70 00:00      
         Here's one without wild casting:            01/01/70 00:00      
            Nothing wild            01/01/70 00:00      
               union misuse            01/01/70 00:00      
                  Not hiding cast            01/01/70 00:00      
                  Programmer knowledge required.            01/01/70 00:00      
                     Hiding of portability issue            01/01/70 00:00      
                     Portability C            01/01/70 00:00      

Back to Subject List