Nearby lessons

106 of 124

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

PointStructureUnion
MemorySum of all members (each has its own space)Only the largest member (all share one space)
WhenAll members are used togetherOnly one member is used at a time
Keywordstructunion
AccessDot 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
CCode Cell
1#include <stdio.h>
2struct item {
3 int i;
4 float f;
5 char c;
6};
7union value {
8 int i;
9 float f;
10 char c;
11};
12void main() {
13 printf("struct item : %d bytes\n", sizeof(struct item));
14 printf("union value : %d bytes\n", sizeof(union value));
15}
Output
struct item : 12 bytes
union value : 4 bytes

Union Shares Memory

In a union, writing one member overwrites the others because they share the same memory:

Example03
CCode Cell
1#include <stdio.h>
2union value {
3 int i;
4 float f;
5 char c;
6};
7void main() {
8 union value v;
9 v.i = 10; // uses the space as an int
10 printf("int : %d\n", v.i);
11 v.f = 3.14; // same space now used as a float
12 printf("float : %.2f\n", v.f);
13}
Output
int   : 10
float : 3.14

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 Questions
Progress: 0 / 2