Structure vs Union in C
"Differentiate between structure and union" is one of the most repeated questions in C exams and interviews. Both group members under one name and use the same . and -> syntax, but they use memory in opposite ways.
In this lesson you will see the difference in a running program, learn a full comparison table for exams, and know exactly when to choose each one.
What You Will Learn
- The one key difference: separate memory vs shared memory.
- How size is calculated for each.
- What happens when you store values in every member.
- A complete comparison table.
- When to use a structure and when to use a union.
- Combining both in one record.
Structure vs Union: The Core Difference
Exam definition: In a structure, each member gets its own memory, so size ≥ sum of members and all members can hold values at once. In a union, all members share one memory block, so size = largest member and only one member holds a value at a time.
Memory trick: Structure = flat with a separate room for each family member: everyone lives there together. Union = one guest room shared by turns: only one person can stay at a time. "Structure = Separate, Union = Unified (shared)."
struct s { int i; char c; float f; }; union u { int i; char c; float f; };
struct: [ i ][c|pad][ f ] union: [ i ]
0 4 8 12 [c]
sizeof = 12 [ f ]
0 4
sizeof = 4
Syntax Comparison
struct student_s union student_u
{ {
int roll; int roll;
float cgpa; float cgpa;
char grade; char grade;
}; };
struct student_s a; union student_u b;
a.roll = 1; b.roll = 1; /* same syntax */
The only change in code is the keyword. The behaviour change is huge.
Example 1: Same Members, Different Behaviour
#include <stdio.h>
struct item_s
{
int code;
float price;
char grade;
};
union item_u
{
int code;
float price;
char grade;
};
int main(void)
{
struct item_s s;
union item_u u;
printf("sizeof(struct) = %zu, sizeof(union) = %zu\n",
sizeof(struct item_s), sizeof(union item_u));
/* structure: all three values survive */
s.code = 101;
s.price = 49.5f;
s.grade = 'A';
printf("struct: code=%d price=%.1f grade=%c\n", s.code, s.price, s.grade);
/* union: each write replaces the previous value */
u.code = 101;
printf("union : code=%d\n", u.code);
u.price = 49.5f;
printf("union : price=%.1f\n", u.price);
u.grade = 'A';
printf("union : grade=%c (code and price are no longer valid)\n", u.grade);
return 0;
}
Output
sizeof(struct) = 12, sizeof(union) = 4 struct: code=101 price=49.5 grade=A union : code=101 union : price=49.5 union : grade=A (code and price are no longer valid)
Code Explanation
- The structure needs 12 bytes (4 + 4 + 1, padded to 12). The union needs only 4, the size of its largest member.
- All three structure members keep their values together, so printing them at the end works.
- In the union, each member is printed immediately after writing. Writing
gradereplaced the first byte, socodeandpriceare now meaningless.
Difference Between Structure and Union (Exam Table)
| Point | Structure | Union |
|---|---|---|
| Keyword | struct | union |
| Memory | Separate memory for each member | Shared memory for all members |
| Size | ≥ sum of all members (with padding) | = largest member (with alignment) |
| Values at a time | All members | Only one member |
| Changing a member | Doesn't affect others | Overwrites the others |
| Initialization | All members can be initialized | Only the first (or one designated) member |
| Member address | Each member at a different offset | All members at the same address |
| Memory usage | More | Less |
| Use when | All fields are needed together (records) | Only one of several fields is needed at a time |
| Example | Student: roll, name, marks | Payment: cash amount or card number or UPI ID |
Example 2: A Structure That Contains a Union
Real programs often combine both. An employee always has an id and a name (structure), but is paid either monthly salary or hourly wages (union), never both.
#include <stdio.h>
struct employee
{
int id;
char name[16];
char type; /* 'M' = monthly, 'H' = hourly */
union
{
float monthly;
struct { float rate; int hours; } hourly;
} pay;
};
float earnings(const struct employee *e)
{
if (e->type == 'M')
return e->pay.monthly;
return e->pay.hourly.rate * e->pay.hourly.hours;
}
int main(void)
{
struct employee staff[2] = {
{1, "Neha", 'M', {.monthly = 45000}},
{2, "Imran", 'H', {.hourly = {250, 120}}}
};
int i;
for (i = 0; i < 2; i++)
printf("%d %-6s %-8s Rs %.2f\n", staff[i].id, staff[i].name,
staff[i].type == 'M' ? "monthly" : "hourly", earnings(&staff[i]));
printf("Union part takes %zu bytes instead of %zu\n",
sizeof(staff[0].pay), sizeof(float) + sizeof(float) + sizeof(int));
return 0;
}
Output
1 Neha monthly Rs 45000.00 2 Imran hourly Rs 30000.00 Union part takes 8 bytes instead of 12
{.monthly = 45000}and{.hourly = {250, 120}}are designated initializers: they pick which union member to set.typeis the tag that tellsearningswhich member is valid.- The pay union uses 8 bytes; separate fields for both pay styles would need 12. With thousands of employees, this adds up.
Important Points to Remember
- Structure = separate memory; union = shared memory.
- Structure size ≥ sum; union size = largest member.
- Structure: all members valid; union: one member valid.
- Same syntax for both: . and ->.
- Union initializer: first member unless designated.
- Combine them: a structure with a tagged union inside.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Saying union size = sum of members | Wrong exam answer | Largest member |
| Saying structure size = exact sum | Ignores padding | "At least the sum" |
| Reading every union member after writing all | Garbage values | Use only the last written |
| Using a union for a student record | Name overwrites marks | Use a structure |
| Union with no tag in a list of mixed data | Can't tell which member to read | Add a type field |
Structure vs Union Practice Questions
- Give four differences between a structure and a union.
- Find sizeof for
struct {char a; double b;}andunion {char a; double b;}on a typical 64-bit system. - Which one would you use to store a student's roll number, name and marks? Why?
- Give a real-life example suitable for a union.
- Can a structure contain a union? Can a union contain a structure?
Show answers
- Memory (separate vs shared), size (≥ sum vs largest), members valid at a time (all vs one), initialization (all vs first/designated), member addresses (different vs same).
- Structure: 16 (1 + 7 padding + 8). Union: 8.
- A structure, because all three values must be stored together.
- A payment field that holds a cash amount, a card number or a UPI ID, only one at a time (or a sensor value that is an int or a float).
- Yes to both.
Coding Exercise
Write a program that prints sizeof of a structure and a union, each with members int a; double b; char c[10];, and explain the numbers in a comment.
Show solution
#include <stdio.h>
struct S { int a; double b; char c[10]; };
union U { int a; double b; char c[10]; };
int main(void)
{
/* struct: 4 (a) + 4 pad + 8 (b) + 10 (c) + 6 pad = 32
union : largest is c (10), rounded up to a multiple of 8 = 16 */
printf("struct S = %zu bytes\n", sizeof(struct S));
printf("union U = %zu bytes\n", sizeof(union U));
return 0;
}
struct S = 32 bytes union U = 16 bytes
Quick Quiz: Structure vs Union (MCQ)
-
Which uses less memory for the same members?
A) Structure B) Union C) Both equal D) Depends on the names
-
In a structure, how many members can hold values at once?
A) One B) All C) Two D) None
-
All members start at the same address in a:
A) Structure B) Union C) Array D) Enum
-
struct {int a; char b;}on a typical system has size:A) 5 B) 8 C) 4 D) 1
-
Best choice to store either an int or a float (never both):
A) Structure B) Union C) Array D) Two variables always
Show answers
- B: union.
- B: all.
- B: union.
- B: 8 (5 bytes of data + 3 padding).
- B: union.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Memory | Structure separate, union shared |
|---|---|
| Size | Structure ≥ sum, union = largest |
| Valid members | Structure all, union one |
| Initialization | Structure all, union first (or designated) |
| Syntax | Same: . and -> |
| Use | Structure for records, union for either-or data |
Frequently asked questions
- What is the main difference between structure and union?
- Structure members have separate memory; union members share the same memory.
- Which is bigger, a structure or a union with the same members?
- The structure (sum of members); the union is only as big as its largest member.
- When should you use a union instead of a structure?
- When only one of the members is needed at a time and memory matters.
Remember
- Structure = Separate rooms; Union = Unified one room.
- Sum vs largest.
Next Topic
Next lesson: typedef in C. You will give types shorter names with typedef.