Accessing union members
What you'll learn: How to store and retrieve data from a union and why the order of these operations matters.
The shared parking spot
Think of a union member as a single, shared parking spot. While your driveway might have room for a motorcycle, a sedan, and a truck all at once (like a struct), a union is a single space that can only hold one vehicle at a time. You can park the motorcycle there, but if you decide to pull the truck in, the motorcycle has to leave.
In C, you access these members using the dot operator (.), just like you do with structures. However, there is a catch: since all members share the exact same memory location, only the most recently assigned member contains valid data.
Syntax and behavior
To assign a value, you name the union variable, followed by a dot and the member name. When you read it back, you must read from the member you most recently "parked" there.
#include <stdio.h>
union Data Holder {
int integer;
float decimal;
char letter;
};
int main() {
union DataHolder u;
// Step 1: Store an integer
u.integer = 42;
printf("Integer: %d\n", u.integer); // Works fine
// Step 2: Store a float (this overwrites the integer!)
u.decimal = 3.14f;
printf("Decimal: %.2f\n", u.decimal); // Works fine
// Step 3: DANGER ZONE
// If we try to read the integer now, we get "garbage"
// because the float is currently sitting in that memory spot.
printf("Integer after float: %d\n", u.integer);
return 0;
}
Why does the data get scrambled?
When you assigned 3.14f to u.decimal, the program went to the union's memory address and wrote the binary pattern for that float. Because u.integer lives at that same address, the original 42 was erased.
If you try to read u.integer while the float is there, C won't stop you, but it will try to interpret the float’s binary bits as an integer. This usually results in a giant, nonsensical number.
To use unions successfully, your code must keep track of which member is currently "active." If you write to the letter, only read from the letter until you assign something else.
Key takeaway
Access union members with the dot operator, but remember that writing to one member overwrites all others.