A struct stores all members side by side, so its size is at least the sum of its members (plus padding) and every member is valid at once. A union stores all members in the same place, so its size is the largest member and only one is valid. Choose a struct for "this and that" data, a union for "this or that".
Remember
struct S { int a; double b; char c; }; /* a AND b AND c */
union U { int a; double b; char c; }; /* a OR b OR c */
Reference
Cheat Sheet
Keep these facts handy while you work with Structures vs Unions in C.
Topic
Detail
Memory
struct: sum plus padding; union: max
Active members
struct: all; union: one
Initialization
union: first member by default
Typical use
struct: records; union: variants
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Enumerations.
Example 1 — Same members, different sizes
Sizes shown are typical for a 64-bit platform.
C
#include <stdio.h>
struct S { int a; double b; char c; };
union U { int a; double b; char c; };
int main(void) {
printf("struct S: %zu bytes\n", sizeof(struct S));
printf("union U: %zu bytes\n", sizeof(union U));
union U u;
u.a = 7;
printf("u.a = %d\n", u.a);
return 0;
}
The union only needs room for its largest member, 8 bytes.
Writing u.a makes a the active member.
Edge Cases & Pitfalls
Check these before relying on Structures vs Unions in real programs.
assume
Assuming sizes
Sizes vary by platform and compiler. Always use sizeof.
mix
Using union fields at once
Setting u.a then u.b overwrites u.a.
Remember
Key Takeaways
struct: AND.
union: OR.
sizeof: verify, never assume.
One line: A struct stores all members side by side, so its size is at least the sum of its members (plus padding) and every member is valid at once.
Frequently Asked Questions
A union, because its members overlap. It is only suitable when members are never needed simultaneously.
Yes. This is the usual way to build a tagged union (variant) type.
Continue with "C Enumerations" next. Give names to related integer constants with enum. The C Structures, Unions and Enums hub lists every topic in order.