Nearby lessons
105 of 124C - Unions
Unions is one of the foundational topics in C programming. This lesson explains Program 6: Unions with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Program 6: Unions
A union looks like a structure but all its members share the same memory. A union uses only enough memory for its largest member.
| Point | Structure | Union |
|---|---|---|
| Memory | Sum of all members (each has its own space) | Only the largest member (all share one space) |
| When | All members can be used together | Only one member is used at a time |
| Keyword | struct | union |
| Access | Dot operator (same) | Dot operator (same) |
Trainer's Note: Simple memory trick: structure gives every member its own room; union gives one room shared by all members. That is why sizeof(struct) is big but sizeof(union) is just the biggest member. Use unions when you store only one of several types at a time.
Example01
📝 Key Takeaways
- Structure groups different types under one name — like a form.
- Define the template, declare variables, access members with the dot.
- Separate programs: access, one-line init, user input, arrays of structures.
- Structures can nest inside structures.
- Union shares one memory for all members; structure gives each member its own.
- sizeof(union) = largest member; sizeof(struct) = sum of members.
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2