The fields in a structure can be sensitive to their defined order. Structures must either be properly ordered or accessed by the field name directly.
When a union has components that could be affected by byte order, use a form similar to that shown in Listing 2-3. Code that sets wch and then reads hi and lo as the high and low bytes of wch will work correctly. The same is true for the reverse direction. Code that sets hi and lo and then reads wch will get the same value on both architectures. For another example, see the WideChar union that’s defined in the IntlResources.h header file.
Listing 2-3 A union whose components can be affected by byte order
union WChar{ |
unsigned short wch; |
struct { |
#if __BIG_ENDIAN__ |
unsigned char hi; |
unsigned char lo; |
#else |
unsigned char lo; |
unsigned char hi; |
#endif |
} s; |
} |
Last updated: 2007-02-26