ARM Technical Support Knowledge Articles

INITIALIZING UNION MEMBERS

Applies to: General Topics

Answer

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.

Article last edited on: 2004-05-08 14:47:41

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential