Nearby lessons

105 of 124

C - 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.

PointStructureUnion
MemorySum of all members (each has its own space)Only the largest member (all share one space)
WhenAll members can be used togetherOnly one member is used at a time
Keywordstructunion
AccessDot 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
CCode Cell
1#include <stdio.h>
2 
3union value {
4 int i;
5 float f;
6 char c;
7}; // memory = size of the largest member
8 
9void main()
10{
11 union value v;
12 
13 v.i = 10; // uses the space as an int
14 printf("int : %d\n", v.i);
15 
16 v.f = 3.14; // same space now used as a float
17 printf("float : %.2f\n", v.f);
18 
19 printf("Size of union : %d bytes\n", sizeof(v));
20}
Output
int : 10 float : 3.14 Size of union : 4 bytes
📝 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 Questions
Progress: 0 / 2