Unions and Type Punning

A union overlays all its members at the same address — its size equals its largest member. Only one member is valid at a time. Used for: tagged unions (discriminated union pattern with a struct wrapping a tag enum + union), type punning (reinterpreting bytes as a different type — technically UB except in specific cases), saving memory when only one variant is needed. The tagged union pattern (struct { enum type tag; union { ... } val; }) is C’s equivalent of algebraic data types / sum types.

Appears In

m04-structs-unions-bitfields