Unions in C
A union stores several members in the same memory — size of the largest, only one valid at a time. It is C's manual variant type: an int-or-float slot, a packet header read two ways, a register split into bytes. Writing one member and reading another reinterprets the bits (type punning), legal in C99+ through unions specifically.
The discipline is tracking which member is live — the classic tagged union pairs an enum tag with the union and switches on it. Without the tag, unions are just overlapping storage waiting to be misread.
Shared storage
union V { int i; float f; }; reserves max(sizeof int, sizeof float) bytes — both members start at the same address.
One live member
Assign .i, and .f holds reinterpreted bits, not a converted value — punning is the feature and the hazard.
Tag your unions
struct { enum Kind k; union V v; } tracks the live member explicitly — readers switch on k before touching v.
Size equals max
sizeof(union) fits only the largest member — the memory saving over structs is the entire point.
#include <stdio.h> union Value { int i; float f;}; int main(void) { union Value v; v.i = 42; printf("%d\n", v.i); printf("%zu\n", sizeof v); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.