← Structs and UnionsC PROGRAMMING 1.4.F

Unions

Shared storage, type punning, and where it is and isn’t safe.

StatusCollected
NotesChapter test: 5/5

A union looks like a struct but means something completely different: every member shares the exact same memory instead of getting its own slice.

union value {
    int i;
    float f;
    char bytes[4];
};

union value v;
v.i = 1;
printf("%d\n", v.bytes[0]);   /* reads the first byte of that same int, byte by byte */

sizeof(union value) is the size of its largest member, not the sum of all of them — because they're all overlapping the same bytes. Writing v.i and then reading v.bytes is type punning: reinterpreting the same bits as a different type, which is exactly how bytes[0] above ends up showing one raw byte of the integer.

It's genuinely useful for exactly that — inspecting raw bytes, or protocol code that treats the same wire data as either a whole value or its component bytes depending on context — but writing one member and reading a different, unrelated one otherwise is asking for undefined behavior and platform-dependent results (endianness, in particular, decides which byte of the int actually lands in bytes[0]).

Notes from readers

Comments — via GitHub