Technical Support

GENERAL: INITIALIZING UNION MEMBERS

QUESTION

How do I initialize the individual members of a union?

ANSWER

To initialize a union at compile time, follow the example as shown here:

union work
  {
  unsigned long a;
  unsigned char b;
  };

#define LONG_VAR  0x01000000
#define CHAR_VAR  1

union work array [] =
  {
    { LONG_VAR },
    { CHAR_VAR },
  };

An ANSI C compiler takes the two expressions, LONG_VAR and CHAR_VAR, and implicitly casts them to the type of the first member of the union. Refer to K&R Second Edition Page 148, last paragraph.

This makes the array appear as follows:

Offset       0    1    2    3
---------------------------------
array [0]    01h  00h  00h  00h
array [1]    00h  00h  00h  01h
---------------------------------
element a    ==================
element b    ====
---------------------------------

From this illustration, the union members are:

array [0].a = 0x01000000
array [0].b = 0x01
array [1].a = 0x00000001
array [1].b = 0x00

Note that only the first union member (a) matches what is normally expected.

While this may SEEM to be incorrect behavior, there is no way for the compiler to determine which element of the union you want to initialize. It is much easier to initialize structures (because you can initialize each member of the structure); however, members of unions overlap and there is no mechanism in C to specify which one to initialize.

Last Reviewed: Saturday, May 08, 2004


Did this article provide the answer you needed?
 
Yes
No
Not Sure