Structure vs Union in C
Both struct and union are user-defined data types in C that group different data types together. However, they differ fundamentally in how they allocate and use memory .
Key Differences Between Structure and Union
| Feature | Structure (struct) | Union |
|---|---|---|
| Keyword | struct | union |
| Memory Allocation | Each member gets its own separate memory | All members share the same memory location |
| Size of the data type | Sum of sizes of all members + padding | Size of the largest member (including padding if any) |
| Number of members active at a time | All members are active simultaneously | Only one member can be used at a time |
| Member access | All members can be accessed independently | Accessing one member overwrites others |
| Initialization | Can initialize all members at once | Only one member can be initialized (usually the first) |
| Default value | Members are undefined unless initialized | All members share same memory – value depends on last written member |
| Use case | Group related but independent data (student record, point, book, etc.) | Memory optimization, type punning, variant types, hardware registers |
| Typical real-world example | struct Student { char name[50]; int roll; float marks; } | union Data { int i; float f; char c; } |
| Memory efficiency | Consumes more memory | Very memory efficient |
Memory Layout Comparison – Visual Example
C
#include <stdio.h>
struct Student {
char grade; // 1 byte
int roll; // 4 bytes
float marks; // 4 bytes
};
union Data {
char grade; // 1 byte
int roll; // 4 bytes
float marks; // 4 bytes
};
int main() {
printf("Size of struct Student: %zu bytes\n", sizeof(struct Student)); // Usually 12 bytes
printf("Size of union Data: %zu bytes\n", sizeof(union Data)); // 4 bytes
return 0;
}
Note: Structure → 12 bytes (with padding), Union → 4 bytes (largest member = float/int)
Practical Demonstration – How Values Behave
C
union Test {
int a;
char b;
};
struct TestStruct {
int a;
char b;
};
// Union: changing one affects others
union Test u;
u.a = 65;
printf("Union int: %d, char: %c\n", u.a, u.b); // 65, 'A'
u.b = 'Z';
printf("After char change → int: %d, char: %c\n", u.a, u.b); // garbage, 'Z'
// Structure: independent
struct TestStruct s;
s.a = 65;
s.b = 'Z';
printf("Struct int: %d, char: %c\n", s.a, s.b); // 65, 'Z' (both preserved)
When to Use Structure vs Union
- Use struct when:
- - You need to store multiple pieces of related data at the same time
- - Examples: Student record, Employee, Point (x,y), Date, Book info
- Use union when:
- - You want to save memory and only one type of data is needed at a time
- - You need to reinterpret the same memory (type punning)
- - Examples: Tagged unions (variant types), Network packet parsing, Hardware register access, Low-level memory manipulation
Modern & Safe Usage (Recommended)
C
enum Type { INT_TYPE, FLOAT_TYPE, CHAR_TYPE };
struct Variant {
enum Type type;
union {
int i;
float f;
char c;
} value;
};
Codecrown