Module 7 · Structures, Unions, Enums and typedef — topic 2 of 4
Unions
A union stores different types in the same memory, one at a time. Learn how unions differ from structures, how to use a tag to track the active member, and where unions are genuinely useful.
Learning objectives
- Explain how a union's members share memory
- Compare sizeof for a struct and a union with the same members
- Build a tagged union to store one of several types safely
Definition
A union is a user-defined type whose members all begin at the same address and overlap in storage; its size is at least that of its largest member, and at most one member holds a meaningful value at any time.
Introduction
A structure reserves space for all of its members. A union reserves space for the largest one only, and every member uses that same space. Writing one member overwrites the others.
That sounds limiting, but it is exactly right when a value can be one of several kinds — a token that is either a number or an operator, or a configuration value that is an int, a float or a string.
Why it matters
Unions appear in compilers, interpreters, network protocols and embedded code where memory is tight or data has variant forms.
“Difference between structure and union” is one of the most frequently asked C viva questions.
Detailed explanation
Syntax mirrors struct: union Value { int i; double d; char s[8]; };. sizeof(union Value) is at least 8 (the largest member), plus any alignment padding.
Only the member you last wrote is meaningful. C allows reading a different member (type punning); the bytes are reinterpreted, which is implementation-specific and best avoided in portable code.
A tagged union pairs a union with an enum (the tag) inside a struct. The tag records which member is active, and code switches on it before reading.
Syntax
- Initialise a union with braces; the first member is set unless you use a designator (
{.f = 1.0f}). - Access members with
.and->as for structs. - Always know which member is active.
Code examples
Struct vs union size
struct: 24 bytes union: 8 bytes
The struct needs room for all three members plus padding; the union only for the 8-byte double.
Writing one member overwrites another
text = A number = 66
More examples
A tagged union for mixed values
int 42 real 3.142 text "hello" sizeof(Value) = 16
Step-by-step explanation
Kindnames the three possible types; it is the tag.- The anonymous union
asholds one ofint,doubleorconst char *in 8 shared bytes. - Designated initialisers (
{.r = 3.14159}) choose which union member to set. print_valueswitches on the tag, so it always reads the member that was written.- The whole
Valueis 16 bytes on a 64-bit system: 4 for the tag, 4 of padding, and 8 for the union.
Expected output
Running “A tagged union for mixed values” prints exactly:
Practical applications
- Interpreters (Lua, CPython internals) store values as tagged unions.
- Network code uses unions to view the same bytes as fields or as a raw buffer.
- Compilers represent syntax-tree nodes of different kinds with tagged unions.
Best practices
- Wrap unions in a struct with a tag and switch on it.
- Use unions to model “one of” data, structs for “all of” data.
- Avoid type punning through unions in portable code; use
memcpyto reinterpret bytes.
Common mistakes
Reading the wrong member
Avoid
Prefer
n.i reinterprets the float's bits as an integer (1069547520 on IEEE systems), not 1.
Expecting all members to keep their values
Avoid
Prefer
If you need every field at once, you need a struct, not a union.
Important notes
- Exact sizes depend on alignment rules; 24 and 16 bytes above are typical for 64-bit desktop compilers.
- C11 anonymous unions let you write
v.iinstead ofv.as.iwhen the union has no name.
Key takeaways
- Union members share the same memory; only one is valid at a time.
- A union's size is about the size of its largest member.
- Track the active member with an enum tag.
Try it yourself
- 1Create a tagged union
Shapeholding either a circle (radius) or a rectangle (width, height) and write a function that returns its area. - 2Print the size of a union containing
char,shortandlong longand explain it.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is the size of a union compared with its members?
- ModerateWhat is printed?
- AdvancedOn a little-endian machine, after `union { uint32_t u; uint8_t b[4]; } x; x.u = 0x11223344;`, what is `x.b[0]`?