Declaring a Union

A union type definition contains the union keyword followed by an optional identifier (tag) and a brace-enclosed list of members.

A union definition has the following form:

>>-union--+-identifier--------------------------+--------------><
          |                    .-----------.    |
          |                    V           |    |
          '-+------------+--{----member--;-+--}-'
            '-identifier-'
 
 

A union declaration has the same form as a union definition except that the declaration has no brace-enclosed list of members.

The identifier is a tag given to the union specified by the member list. Once a tag is specified, any subsequent declaration of the union (in the same scope) can be made by declaring the tag and omitting the member list. If a tag is not specified, all variable definitions that refer to that union must be placed within the statement that defines the data type.

The list of members provides the data type with a description of the objects that can be stored in the union.

A union member definition has same form as a variable declaration.

A member of a union can be referenced the same way as a member of a structure.

For example:

union {
      char birthday[9];
      int age;
      float weight;
      } people;
 
people.birthday[0] = '\n';

assigns '\n' to the first element in the character array birthday, a member of the union people.

A union can represent only one of its members at a time. In the example, the union people contains either age, birthday, or weight but never more than one of these. The printf statement in the following example does not give the correct result because people.age replaces the value assigned to people.birthday in the first line:

#include <stdio.h>
#include <string.h>
 
union {
  char birthday[9];
  int age;
  float weight;
} people;
 
int main(void) {
  strcpy(people.birthday, "03/06/56");
  printf("%s\n", people.birthday);
  people.age = 38;
  printf("%s\n", people.birthday);
}

The output of the above example will be similar to the following:

03/06/56
&

Related References

IBM Copyright 2003