Skip to main content
A typedef union in C is a composite declaration that defines a memory-sharing data structure and simultaneously assigns it a user-defined type alias. By combining the union keyword (which allocates a single shared memory space for multiple members) with the typedef keyword (which creates a type alias), developers can instantiate variables of this type without repeatedly using the union keyword in the declaration. Syntax and Structure The standard declaration of a typedef union follows this structure:
  • optional_tag: The internal identifier for the union. It can be omitted (creating an anonymous union bound to the typedef) unless the union needs to self-reference via pointers.
  • AliasName: The new type identifier used to declare variables.
Declaration Comparison Without typedef, declaring a variable requires the union keyword in the type specifier:
With typedef, the alias acts as a standalone type specifier:
Memory Layout and Mechanics When a variable of a typedef union is instantiated, the compiler enforces strict memory overlapping rules:
  1. Shared Base Address: Every member of the union begins at the exact same memory address. The offset of every member from the beginning of the union is zero.
  2. Size Determination: The sizeof the entire typedef union is equal to the size of its largest member, plus any additional bytes required to satisfy the strict alignment requirements of the target architecture (padding).
  3. Mutual Exclusion: Because members share the same memory footprint, assigning a value to one member overwrites the underlying byte representation of all other members. Reading from a member other than the one most recently written to results in type punning, where the compiler interprets the raw bytes according to the newly accessed member’s type.
Example of Memory Mechanics
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More