A union declares several members that share the same memory. Its size is the size of the largest member, and only the most recently written member holds a meaningful value. Use unions with a tag field (tagged union) to save space when only one of several representations is active.
Remember
union Number {
int i;
double d;
};
union Number n;
n.i = 42; /* now n.d is not meaningful */
Reference
Cheat Sheet
Keep these facts handy while you work with Unions in C.
Topic
Detail
Size
Largest member (plus padding)
Active member
The last one written
Tag
Store which member is valid
Reading another member
Reinterprets the bytes
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Structures vs Unions.
Example 1 — A tagged union
The kind field records which member is valid.
C
#include <stdio.h>
struct Number {
enum { AS_INT, AS_DOUBLE } kind;
union {
int i;
double d;
} value;
};
static void show(struct Number n) {
if (n.kind == AS_INT) printf("int: %d\n", n.value.i);
else printf("double: %.1f\n", n.value.d);
}
int main(void) {
struct Number a = {AS_INT, {.i = 42}};
struct Number b = {AS_DOUBLE, {.d = 3.5}};
show(a);
show(b);
printf("sizeof value = %zu\n", sizeof a.value);
return 0;
}
Output
int: 42
double: 3.5
sizeof value = 8
How It Works
kind says whether to read i or d.
The union occupies 8 bytes (the size of double), not 12.
Designated initializers pick the member to set.
Edge Cases & Pitfalls
Check these before relying on Unions in real programs.
read
Reading the wrong member
Without a tag you cannot tell which member is valid. Reading the wrong one gives meaningless data.
endian
Type punning is not portable
Viewing an int as bytes depends on endianness and padding.
Remember
Key Takeaways
Share: one block, many views.
Tag: track the active member.
Size: largest member.
One line: A union declares several members that share the same memory.
Frequently Asked Questions
A union is a type whose members all occupy the same memory location, so it holds one value at a time and has the size of its largest member.
Use unions to save memory with mutually exclusive alternatives, such as variant records or token values, and always pair them with a tag.
Continue with "C Structures vs Unions" next. Compare memory use and behavior of structs and unions. The C Structures, Unions and Enums hub lists every topic in order.