A union lets several members share one storage region. Its size is sufficient for its largest member, but normally only the most recently written member is considered active. It represents “one of several forms,” so the program must separately track which form is current.
#include <stdio.h>
union Value {
int whole;
double decimal;
char letter;
};
int main(void) {
union Value value;
value.whole = 42;
printf("whole: %d\n", value.whole);
value.decimal = 3.5;
printf("decimal: %.1f\n", value.decimal);
value.letter = 'Z';
printf("letter: %c\n", value.letter);
return 0;
}After writing decimal, do not assume the earlier whole still contains 42. Members overlap the same region; reading a non-current member interprets the same object representation as another type and is not a normal data conversion.
INTERACTIVE LAB
One storage region, three member views
ACCESSFREE
All three members start at the same address. Assign a member to reinterpret the same storage, not to create another copy.
union Value {
int whole;
double decimal;
char letter;
};
union Value value;
No member has been assigned
This illustration assumes 4-byte int, 8-byte double, 1-byte char, and an 8-byte union; use sizeof for actual sizes. Color shows the current member's write range, not byte values. Unhighlighted bytes are not guaranteed to be zero and must not be used to recover old members.Choose an assignment. Its highlighted range starts at the same address and changes with the member type.
KNOWLEDGE QUIZ
QUESTION
Why can code no longer rely on value.whole's old value after assigning value.decimal?