Skip to main content
A union in C is a user-defined composite data type that allows multiple members of different types to occupy the exact same memory location. Unlike a struct, where each member is allocated its own distinct memory space sequentially, a union allocates a single shared block of memory. The total size of a union is determined by the size of its largest member, potentially adjusted for memory alignment requirements. Because all members share this single memory space, a union can only hold a valid value for one of its members at any given time.

Syntax

A union is defined using the union keyword, followed by an optional tag and a block containing member declarations.

Memory Allocation and Sizing

When the compiler allocates memory for a union, it calculates the sizeof each member and reserves an amount of memory equal to the largest member.
Note: The compiler may add padding bytes to the total size of the union to satisfy the alignment requirements of its strictest member.

Member Access and Data Overwriting

Members of a union are accessed using the dot operator (.) for direct instances, or the arrow operator (->) for pointers to a union. Because the memory is shared, writing to a new member inherently overwrites the bit pattern of the previously stored member. Reading from a member other than the one most recently written to results in undefined behavior or yields a reinterpreted bit pattern (type punning).

Initialization

By default, standard C rules dictate that initializing a union with a brace-enclosed list will initialize its first declared member. To initialize a different member at the time of declaration, C99 introduced designated initializers.

Pointers to Unions

Pointers to unions behave identically to pointers to structs. The pointer holds the base memory address of the union, which is simultaneously the base address of every single member within that union.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More