Structure vs Union in C
Bothstruct and union are user-defined data types in C that group multiple members together. They differ fundamentally in how memory is allocated and how members are accessed.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Key differences between struct and union in C
struct and union are user-defined data types in C that group multiple members together. They differ fundamentally in how memory is allocated and how members are accessed.
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Keyword | struct | union |
| Memory | Own memory per member | Shared memory |
| Size | Sum of all members | Size of largest member |
| Values held | All at once | Only the last-written one |
| Access | Multiple at once | One at a time |
| Initialization | Multiple members | Only the first member |
| Use case | Group related fields of different types | Store one of several types at a time |
struct S {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};
// sizeof(struct S) ≈ 12 bytes (with padding)
// Each member at a different address
union U {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};
// sizeof(union U) = 4 bytes (largest member)
// All members share the same address
#include <stdio.h>
struct S { int a; float b; };
union U { int a; float b; };
int main() {
struct S s;
union U u;
s.a = 10; s.b = 3.14f;
u.a = 10; u.b = 3.14f;
// struct: both values preserved
printf("Struct: a=%d, b=%.2f\n", s.a, s.b);
// union: only b is valid (overwrote a)
printf("Union : a=%d, b=%.2f\n", u.a, u.b);
printf("Size of struct S = %lu bytes\n", sizeof(s));
printf("Size of union U = %lu bytes\n", sizeof(u));
return 0;
}
Struct: a=10, b=3.14
Union : a=1078523331, b=3.14 ← a is garbage (overwritten)
Size of struct S = 8 bytes
Size of union U = 4 bytes
enum Week {
Monday, // 0
Tuesday, // 1
Wednesday, // 2
Thursday, // 3
Friday, // 4
Saturday, // 5
Sunday // 6
};
enum Level {
LOW = 1,
MEDIUM = 5,
HIGH = 10
};
#include <stdio.h>
enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main() {
enum Week today = Wednesday;
printf("Day number: %d", today); // Output: 2
return 0;
}