C Notes
Complete guide to unions in C programming — definition, syntax, shared memory concept, difference between struct and union, practical examples, type punning, tagged unions, and interview questions.
A union looks almost identical to a structure in syntax, but its behavior is fundamentally different. While a struct allocates separate memory for each member, a union stores all members in the same memory location. Only one member can hold a valid value at any time.
What is a Union?
All members share the same starting address. Writing to one member overwrites the others.
Memory Comparison: Struct vs Union
Basic Union Example
Size of union: 20 bytes data.i = 42 data.f = 3.14 data.i = 1078523331 (corrupted!) data.str = Hello data.i = 1819043144 (corrupted!) data.f = 1143139122437582505939828736.000000 (corrupted!)
Struct vs Union — Complete Comparison
| Feature | struct | union |
|---|---|---|
| Memory | Sum of all members (+ padding) | Size of largest member |
| Members active | All simultaneously | Only one at a time |
| Access | Any member anytime | Only last-written member |
| Use case | Group related data | Variant/alternative types |
| Syntax | struct Name {} | union Name {} |
Practical Use: Tagged Union (Variant Type)
The most common real-world use of unions is a tagged union — a union paired with a tag indicating which member is currently valid:
Value 0 → Integer: 42 Value 1 → Float: 3.14 Value 2 → String: "Hello World"
Type Punning with Unions
Unions allow you to reinterpret the same bits as different types:
#include <stdio.h>
union FloatBits {
float f;
unsigned int bits;
};
int main() {
union FloatBits fb;
fb.f = 3.14f;
printf("Float: %f\n", fb.f);
printf("Bits: 0x%08X\n", fb.bits);
printf("Binary representation of 3.14f in IEEE 754\n");
// Detect sign, exponent, mantissa
int sign = (fb.bits >> 31) & 1;
int exp = (fb.bits >> 23) & 0xFF;
int mantissa = fb.bits & 0x7FFFFF;
printf("Sign: %d, Exponent: %d, Mantissa: 0x%06X\n", sign, exp, mantissa);
return 0;
}Float: 3.140000 Bits: 0x4048F5C3 Binary representation of 3.14f in IEEE 754 Sign: 0, Exponent: 128, Mantissa: 0x48F5C3
Union for Memory-Efficient Storage
#include <stdio.h>
struct Event {
int type; // 1 = keyboard, 2 = mouse, 3 = timer
union {
struct { int key_code; int modifiers; } keyboard;
struct { int x; int y; int button; } mouse;
struct { int timer_id; float elapsed; } timer;
} data;
};
int main() {
struct Event e;
// Mouse click event
e.type = 2;
e.data.mouse.x = 150;
e.data.mouse.y = 300;
e.data.mouse.button = 1;
printf("Event type: Mouse\n");
printf("Position: (%d, %d), Button: %d\n",
e.data.mouse.x, e.data.mouse.y, e.data.mouse.button);
printf("\nSize of Event: %zu bytes\n", sizeof(struct Event));
printf("(Without union it would be much larger)\n");
return 0;
}Event type: Mouse Position: (150, 300), Button: 1 Size of Event: 16 bytes (Without union it would be much larger)
Anonymous Unions (C11)
Token value: 42
Interview Questions
Q1: What is the size of a union?
The size of a union equals the size of its largest member (plus any padding needed for alignment). All members share the same memory, so the union must be large enough to hold the biggest one.
Q2: Can you access all union members at the same time?
No. Only the last-written member contains a valid value. Reading any other member after writing a different one is technically undefined behavior (though type punning through unions is widely supported by compilers as an extension).
Q3: What is a tagged union and why is it useful?
A tagged union pairs a union with an enum/int "tag" that records which member is currently valid. This implements variant/sum types safely — the tag prevents you from reading the wrong member. It's used in interpreters, event systems, and protocol parsers.
Q4: When would you use a union instead of a struct?
When you have multiple possible representations for a piece of data, but only one is active at a time. Examples: a JSON value (int OR float OR string), a network packet (TCP OR UDP header), a hardware register with bitfield and integer interpretations.
Q5: Is it safe to use unions for type punning?
In standard C (C99+), reading a union member other than the last one written is implementation-defined (not strictly undefined). Most compilers (GCC, Clang) explicitly support this as an extension. It's commonly used for inspecting float bits, network byte manipulation, etc.
Summary
- Unions store all members at the same memory address — only one is valid at a time
- Union size = size of the largest member
- Use tagged unions (union + enum tag) for type-safe variants
- Useful for memory-efficient event systems, protocol parsing, and hardware registers
- Type punning through unions lets you reinterpret bits (widely supported)
- Anonymous unions (C11) allow direct member access without naming the union
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Unions in C – Shared Memory Data Types.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, structures, and, unions, unions in c – shared memory data types
Related C Programming Topics