C Language | Structure Declarations | Unions

A union resembles a structure, but all members share the same storage. Its size is sufficient for its largest member.

Sharing Memory Between Types

Declare a union with the union keyword.

union tag_name {
  type member_name;
  ...
} variable_name;

Members are accessed like structure members, but they have the same address.

#include <stdio.h>

union Value {
  unsigned char chValue;
  int iValue;
};

int main() {
  union Value u;
  u.iValue = 0xFFFF;
  printf("chValue = %08X : &chValue = %p\n"
         "iValue = %08X : &iValue = %p\n",
         u.chValue, (void *)&u.chValue, u.iValue, (void *)&u.iValue);
  return 0;
}

The result depends on representation details such as byte order. Unions can also contain structures, arrays, and other unions. A matrix can therefore be exposed both as named fields and as an indexed array.

Initializing a Union

Because members share storage, initialize one member at a time. An initializer without a designator initializes the first member.

union Point {
  struct {
    short int x, y;
  } point;
  int location;
};

union Point u = { { 100, 50 } };

Code that interprets packed values this way depends on type sizes and byte order. Use it only when those assumptions are explicit.