C ยท Chapter 31 of 45

C Unions

A union looks similar to a struct syntactically, but all its members share the same memory location. This means a union only needs enough memory for its largest member, and only one member is valid at a time.

Unions are often used to save memory when you know only one of several possible types will be needed at any given moment, such as in variant types or low-level hardware programming.

Syntax
union Name {
  type member1;
  type member2;
};

Defining a union

A union is declared just like a struct but with the `union` keyword. All members overlap the same memory, so writing to one member can overwrite the data of another.

Union vs struct

A struct allocates separate memory for each member, so its size is the sum of all members. A union allocates memory equal to its largest member, since members share that space.

Example 1 (c)
#include <stdio.h>

union Data {
  int i;
  float f;
};

int main() {
  union Data d;
  d.i = 10;
  printf("%d\n", d.i);
  return 0;
}
Output
10

Writing to d.i stores 10 in the shared memory of the union.

Example 2 (c)
#include <stdio.h>

union Data { int i; float f; };

int main() {
  printf("%lu %lu\n", sizeof(union Data), sizeof(int));
  return 0;
}
Output
4 4

The union's size equals its largest member (int and float are both 4 bytes here).

Key points

  • All union members share the same memory location.
  • A union's size equals the size of its largest member.
  • Only one union member should be treated as valid at a time.
  • Unions are useful for memory-efficient variant data.
๐Ÿ’ก Note: Reading a union member different from the one last written is technically undefined behavior in standard C, though it's used in practice for type-punning.

๐Ÿ“ Quick Quiz

1. How much memory does a union typically use?

2. How many union members hold valid data at once (in normal usage)?

3. What keyword declares a union?