C Programming

Lesson 5 of 11

Unions

If you know TypeScript, a "union type" there means a value that could be one of several different types (string | number), and the compiler tracks which. A C union is a completely different, much lower-level idea: it's a block of memory that all its members share, one at a time.

C

Unlike a struct, where every member gets its own space (so the struct's total size is the sum of its members), a union's members all overlap the same bytes. Its total size is only as big as its largest member, because only one member is ever "live" at a time, writing to one member overwrites whatever was in the others.

Why use one?

Unions save memory when you need to represent "this is either an A or a B, never both at once" without wasting space storing both. They're commonly paired with a separate "tag" field (often an enum) to remember which member is currently valid, since the union itself has no idea:

C

This "tagged union" pattern is exactly how many interpreters and virtual machines represent dynamically-typed values internally, worth remembering, you'll build something very close to it later in this course.

📝 Unions Quiz

Passing score: 70%
  1. 1.What is the size of a C union roughly equal to?

  2. 2.A C union's members occupy separate, non-overlapping memory, similar to a struct.

  3. 3.Pairing a union with an enum "tag" field to remember which member is currently valid is called a ____ union.