📘 Unions in C Programming – Memory Explanation, Fully Commented Programs, Viva Questions & MCQs (Beginner to Advanced Guide)
🧑💻 Introduction
In C programming, we use structures to store different data types together.
But sometimes:
-
We need to store different data types
-
Only one value is required at a time
-
Memory optimization is important
👉 That’s where Union comes into the picture.
A Union is a user-defined data type in C where:
🧠 All members share the same memory location.
This makes union memory-efficient compared to structures.
In this complete beginner to advanced guide, you will learn union memory concepts, fully commented programs, viva questions, MCQs, and real-world applications.
📌 What is a Union in C?
A Union is a special data type that allows storing different types of data in the same memory location, but only one member can hold a value at a time.
Unlike structure:
Structure → separate memory
Union → shared memory
Internally, the compiler allocates memory equal to the largest member and all other members reuse that same memory space starting from the same base address.
🔹 Syntax of Union
union UnionName // Declare union
{
data_type member1; // First member
data_type member2; // Second member
data_type member3; // Third member
};
🧠 Memory Concept of Union (Very Important)
🧠 How Union Saves Memory (Visual Explanation)
Before understanding unions deeply, let’s visually compare how memory is allocated in structure and union. This diagram clearly shows why unions are memory-efficient and how members share the same memory block.
🔍 What This Diagram Shows
1️⃣ In a structure, each member gets separate memory.
👉 Total size = sum of all members + padding.
2️⃣ In a union, all members share the same memory location.
👉 Total size = size of the largest member.
3️⃣ When a new value is assigned in a union,
⚠ The previous value is overwritten.
🚨 In a union, only one member holds a valid value at a time.
💡 Note: The structure size may include padding for memory alignment, while union size depends only on its largest member.
In union, all members start at the same base address.
🔸 Structure
-
Each member has separate memory.
-
Total size = Sum of all members (plus padding).
🔸 Union
-
All members share same memory block.
-
Total size = Size of largest member.
📌 When one member is updated, the previous value is overwritten.
💻 Program 1: Basic Union Example (Fully Commented)
#include <stdio.h> // Header file for input-output functions
union Data // Define a union named Data
{
int i; // Integer member
float f; // Float member
char str[20]; // Character array member
};
int main() // Main function starts
{
union Data data; // Declare union variable
data.i = 10; // Assign integer value
printf("Integer: %d\n", data.i); // Print integer value
data.f = 3.14; // Assign float value (overwrites integer)
printf("Float: %.2f\n", data.f); // Print float value
return 0; // End program
}
📌 Observation:
Assigning data.f overwrites data.i because memory is shared.
✅ Expected Output
Integer: 10
Float: 3.14
📌 Explanation:
After assigning data.f = 3.14, the previous integer value is overwritten because both members share the same memory.
📏 Program 2: Checking Size of Union (Fully Commented)
#include <stdio.h> // Standard I/O header
union Example // Define union
{
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};
int main() // Main function
{
printf("Size of union: %lu", sizeof(union Example)); // Print union size
return 0; // End program
}
✅ Expected Output (Usually)
Size of union: 4
📌 Explanation:
Largest member = int (4 bytes) or float (4 bytes)
So union size = 4 bytes.
(Note: It may vary slightly depending on compiler/system.)
🔍 Structure vs Union – Complete Comparison
| Feature | Structure | Union |
|---|---|---|
| Memory Allocation | Separate memory for each member | Shared memory for all members |
| Total Size | Sum of sizes of all members | Size of largest member only |
| Data Storage | All values stored at once | Only one value stored at a time |
| Memory Efficiency | Less efficient | More efficient |
| Risk of Overwrite | No | Yes |
| Keyword Used | struct | union |
| Access to Members | All members accessible anytime | Only last assigned member reliable |
| Initialization | Multiple members can be initialized | Only one member can be initialized |
| Use Case | When all data needed together | When only one data needed at a time |
| Programming Safety | Safer | Less safe if misused |
💪 Practice Programs on Union (New Section)
💻 Practice Program 1
Demonstrating How Union Members Overwrite Each Other
This program shows how assigning a new value to one union member overwrites the previous value because all members share the same memory location.
#include <stdio.h> // Input-output header
union Info // Define union
{
int age; // Integer member
float salary; // Float member
char grade; // Character member
};
int main() // Main function
{
union Info person; // Declare union variable
person.age = 25; // Assign age
printf("Age: %d\n", person.age); // Print age
person.salary = 50000.50; // Assign salary (overwrites age)
printf("Salary: %.2f\n", person.salary); // Print salary
person.grade = 'A'; // Assign grade (overwrites salary)
printf("Grade: %c\n", person.grade); // Print grade
return 0; // End program
}✅ Expected Output
Age: 25
Salary: 50000.50
Grade: A📌 Explanation:
Each new assignment overwrites the previous value because union members share memory.
💻 Practice Program 2
Finding the Size of a Union
This program demonstrates that the size of a union is equal to the size of its largest data member.
#include <stdio.h> // Header file
union Test // Define union
{
int a; // Integer member
double b; // Double member (largest)
char c; // Character member
};
int main() // Main function
{
printf("Size of union: %lu bytes\n", sizeof(union Test)); // Print size
return 0; // End
}✅ Expected Output (Usually)
Size of union: 8 bytes📌 Explanation:
Largest member =
double(usually 8 bytes)
So union size = 8 bytes.
💻 Practice Program 3 (Union Inside Structure)
Using a Union Inside a Structure
This program shows how a union can be declared inside a structure to save memory when only one value is needed at a time.
#include <stdio.h> // Header file
struct Student // Define structure
{
int roll; // Roll number
union // Anonymous union
{
int marks; // Marks
char grade; // Grade
} result; // Union variable inside struct
};
int main() // Main function
{
struct Student s; // Declare struct variable
s.roll = 101; // Assign roll number
s.result.marks = 85; // Assign marks
printf("Roll: %d\n", s.roll); // Print roll
printf("Marks: %d\n", s.result.marks); // Print marks
return 0; // End
}✅ Expected Output
Roll: 101
Marks: 85📌 Explanation:
Here, only
marksis assigned, so it prints correctly.
💻 Practice Program 4 (Structure Inside Union)
Declaring a Structure as a Member of a Union
This program demonstrates how a structure can be included inside a union and how assigning one member overwrites another.
#include <stdio.h> // Header
struct Address // Define structure
{
int houseNo; // House number
char city[20]; // City name
};
union Data // Define union
{
int id; // ID member
struct Address addr; // Structure member
};
int main() // Main function
{
union Data d; // Declare union variable
d.id = 1001; // Assign ID
printf("ID: %d\n", d.id); // Print ID
d.addr.houseNo = 221; // Assign house number (overwrites ID)
printf("House No: %d\n", d.addr.houseNo); // Print house number
return 0; // End
}✅ Expected Output
ID: 1001
House No: 221📌 Explanation:
After assigning
addr.houseNo, the previousidvalue is overwritten.
💻 Practice Program 5 (Union Passed to Function)
Passing a Union Variable to a Function
This program shows that a union can be passed to a function just like a structure, either by value or by reference.
#include <stdio.h> // Header file
union Number // Define union
{
int i; // Integer member
float f; // Float member
};
void display(union Number n) // Function receiving union
{
printf("Integer value: %d\n", n.i); // Print integer
}
int main() // Main function
{
union Number num; // Declare union variable
num.i = 50; // Assign integer value
display(num); // Pass union to function
return 0; // End program
}✅ Expected Output
Integer value: 50📌 Explanation:
The union is passed by value, and the integer member is printed.
🌍 Real-Life Example of Union
Suppose we are designing a Payment System.
A person can pay using:
-
Cash
-
Credit Card
-
UPI
But at one time, only one method is used.
union Payment // Define a union named Payment { int cash; // Stores cash amount (used when payment is made by cash) long cardNumber; // Stores credit/debit card number (used for card payment) char upiID[20]; // Stores UPI ID as a string (used for UPI payment) }; // End of union definition
This saves memory because only one payment method is active at a time.
🧑🏫 Detailed Viva Questions on Union (With Answers)
✅ Q1. What is a Union in C?
A union is a user-defined data type where all members share the same memory location. Only one member can contain a valid value at a time.
✅ Q2. What is the main difference between structure and union?
Structure allocates separate memory to each member, while union shares memory among all members.
✅ Q3. How is the size of a union calculated?
The size of a union equals the size of its largest member.
✅ Q4. Can we access all members at the same time?
No. Only one member can be used at a time.
✅ Q5. Why do we use union?
Union is used for memory optimization, especially in embedded systems and hardware-level programming.
✅ Q6. What happens if we access inactive member?
It may produce a garbage value or undefined behavior.
✅ Q7. Can union be inside structure?
Yes. A union can be declared inside a structure.
✅ Q8. Can structure be inside union?
Yes. A structure can be a member of a union.
✅ Q9. What are disadvantages of union?
-
Only one active member
-
Risk of overwrite
-
Can confuse beginners
✅ Q10. Where are unions used in real applications?
-
Embedded systems
-
Communication protocols
-
Device drivers
-
Memory-sensitive programs
🧠 10 Advanced Trick Viva Questions
1️⃣ Can union contain pointers? → ✅ Yes
A union member can be a pointer variable like int *ptr because pointers are valid data types in C.
2️⃣ Can union contain array? → ✅ Yes
Arrays can be declared as union members just like in structures.
3️⃣ Can union contain another union? → ✅ Yes
A union can include another union as one of its members (nested union).
4️⃣ Can union be global? → ✅ Yes
A union can be declared outside all functions and used globally in the program.
5️⃣ Can union be passed to function? → ✅ Yes
Union variables can be passed to functions either by value or by reference (pointer).
6️⃣ Can multiple members be initialized? → ❌ Only first member directly
In C, only the first member of a union can be initialized at declaration time.
7️⃣ Is union faster than structure? → ❌ Not necessarily
Union saves memory but does not automatically improve execution speed.
8️⃣ Does union support nesting? → ✅ Yes
A union can contain another union or structure inside it.
9️⃣ Can union contain structure? → ✅ Yes
A structure can be a member of a union.
🔟 Is union object-oriented? → ❌ No
Union is a feature of procedural C programming, not object-oriented programming.
📝 15 MCQs on Union in C (With Answers & Explanation)
1. Union size depends on:
A) Sum
B) Largest member
C) Smallest member
D) None
✅ Answer: B) Largest member
📘 Explanation: The size of a union equals the size of its largest data member.
2. How many members can store value at once?
A) All
B) Two
C) One
D) None
✅ Answer: C) One
📘 Explanation: Only one member can hold a valid value at a time because all members share the same memory.
3. Union is mainly used for:
A) Speed
B) Memory saving
C) Looping
D) Security
✅ Answer: B) Memory saving
📘 Explanation: Union allows multiple variables to share the same memory space, reducing memory usage.
4. Union keyword is:
A) struct
B) union
C) enum
D) typedef
✅ Answer: B) union
📘 Explanation: The keyword union is used to declare a union in C.
5. Members of union share:
A) Separate memory
B) Same memory
C) Heap memory
D) Stack memory
✅ Answer: B) Same memory
📘 Explanation: All members of a union use the same memory location.
6. Can union contain structure?
A) Yes
B) No
C) Only in C++
D) None
✅ Answer: A) Yes
📘 Explanation: A union can contain structures, arrays, and other data types as members.
7. Union size of (int, char)?
A) 1
B) 4
C) 5
D) 8
✅ Answer: B) 4
📘 Explanation: Since int is larger than char, the union size becomes the size of int (usually 4 bytes).
8. Is union memory efficient?
A) Yes
B) No
✅ Answer: A) Yes
📘 Explanation: Union is memory efficient because it stores only one member at a time in shared memory.
9. Can union be global?
A) Yes
B) No
✅ Answer: A) Yes
📘 Explanation: A union can be declared globally just like structures and variables.
10. Can union be nested?
A) Yes
B) No
✅ Answer: A) Yes
📘 Explanation: A union can be nested inside another union or structure.
11. Can we use sizeof on union?
A) Yes
B) No
✅ Answer: A) Yes
📘 Explanation: The sizeof operator can be used to determine the size of a union.
12. Does union allow multiple active members?
A) Yes
B) No
✅ Answer: B) No
📘 Explanation: Only one member can be active at a time because they share the same memory block.
13. Largest member determines:
A) Speed
B) Size
C) Security
D) Loop
✅ Answer: B) Size
📘 Explanation: The largest member in a union determines the total memory size allocated.
14. Union overwrites data because:
A) Separate memory
B) Shared memory
C) Dynamic memory
D) Stack
✅ Answer: B) Shared memory
📘 Explanation: When a new value is assigned, it overwrites the previous data stored in the shared memory.
15. Union is best used in:
A) Web design
B) Embedded systems
C) Animation
D) Gaming
✅ Answer: B) Embedded systems
📘 Explanation: Unions are commonly used in embedded systems where memory optimization is critical.
🏆 Advantages of Union
✔ Memory efficient
✔ Useful in embedded systems
✔ Reduces memory consumption
✔ Good for low-level programming
❌ Disadvantages of Union
✖ Only one active member
✖ Risk of data loss
✖ Can create confusion
🎓 Final Interview-Ready Summary
🔹 Union is a user-defined data type
🔹 All members share same memory
🔹 Only one value stored at a time
🔹 Size equals largest member
🔹 Used for memory optimization
If structure organizes data,
👉 Union optimizes memory.
📌 Keep Learning. Keep Coding. Keep Growing.
✨ Written by Krishna Popat
🌱 Founder, Learning Growth Hub
Comments
Post a Comment