The danger of reading the wrong union member
What you'll learn: Why reading a union member different from the one you last assigned results in "garbage" data or unexpected values.
One locker, many outfits
Imagine a gym locker that is only big enough to hold one item at a time. If you put a pair of boots in the locker, the locker contains boots. If you later decide to shove a silk shirt into that same tiny space, the boots are tossed out. The locker now holds a shirt.
In C, a union is that locker. All members of a union share the exact same memory address. The "danger" arises when you put a "shirt" (an integer) into the locker, but then try to put it on as if it were "boots" (a float). The computer won't stop you, but you’ll end up looking very silly—or crashing your program.
The Bit Buffet
Because all members share the same memory, they interpret the same underlying binary bits differently. A pattern of 0s and 1s that represents the integer 1065353216 is the exact same pattern that represents the decimal 1.0 in floating-point math.
If you store a value as one type and read it as another, C doesn't convert the value for you. It simply hands you the raw bits and says, "Here, try to make sense of this."
#include <stdio.h>
union Data {
int integer;
float decimal;
};
int main() {
union Data myData;
// We store a float
myData.decimal = 1.0f;
// DANGER: We are reading it as an integer!
// This will NOT print "1".
// It prints the integer interpretation of the float's bits.
printf("Stored 1.0 as a float, but reading as int: %d\n", myData.integer);
return 0;
}
Why this happens
When you write to myData.decimal, the computer writes 32 bits to memory in a format called IEEE 754 (the standard for decimals). When you ask for myData.integer, the computer looks at those exact same 32 bits but interprets them using two's complement (the standard for integers).
The result is usually a giant, nonsensical number. This is called type punning, and while advanced programmers sometimes do it on purpose, doing it by accident is a leading cause of logic bugs. C does not keep track of which member was "active," so the responsibility is entirely on you to remember what you last stored.
Key takeaway
A union only holds one value at a time; reading a member you didn't recently set will return misinterpreted raw bits rather than a meaningful value.