Nearby lessons
106 of 124C - Structures vs Unions
Compare structures and unions in C — how each one uses memory and when to choose which. The key difference: a structure gives every member its own space, a union makes all members share one space.
The One-Line Difference
| Point | Structure | Union |
|---|---|---|
| Memory | Sum of all members (each has its own space) | Only the largest member (all share one space) |
| When | All members are used together | Only one member is used at a time |
| Keyword | struct | union |
| Access | Dot operator (same) | Dot operator (same) |
In simple words: structure gives every member its own room; union gives one room shared by all members.
Size Difference in Action
Run this and compare the sizes:
Example02
Union Shares Memory
In a union, writing one member overwrites the others because they share the same memory:
Example03
When to Use Which
- Use a structure when you need all the fields together — a student record with roll number, name, and marks.
- Use a union when you store only one of several types at a time — a value that can be an int or a float or a char.
- Unions save memory — but only if you never need two members at once.
📝 Key Takeaways
- Structure gives every member its own memory
- Union shares one memory for all members
- sizeof(struct) is the sum; sizeof(union) is the largest member
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2