Learn C
#include "structstypes/unions.h"

Unions in C

#concept

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.

#how it works
1

Shared storage

union V { int i; float f; }; reserves max(sizeof int, sizeof float) bytes — both members start at the same address.

2

One live member

Assign .i, and .f holds reinterpreted bits, not a converted value — punning is the feature and the hazard.

3

Tag your unions

struct { enum Kind k; union V v; } tracks the live member explicitly — readers switch on k before touching v.

4

Size equals max

sizeof(union) fits only the largest member — the memory saving over structs is the entire point.

#example
#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;
}
Output
42
4
1v.i = 42 stores through the int member — the live member is now i.
2Reading .i back yields 42; reading .f instead would reinterpret the same bits as float.
3sizeof reports 4 — one int's worth of storage shared by both members.
#use cases
Variant values (int-or-float configs) with enum tags
Hardware registers read as whole words and bit-fields simultaneously
Packet headers interpreted under multiple layouts
Memory-frugal tables where alternatives never coexist

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.