One Value in Shared Storage
One storage space, two possible values
The workshop's old counter sometimes records a number, sometimes a letter. A struct has room for both fields at once; a union makes them share storage. Treat the member you most recently stored as the value to read. The example prints count while that member holds 7, then switches to grade.
The initializer {.count = 7} names the member explicitly. This is a designated initializer: the dot and member name say where the initial value goes. It works for structures too. We read only the last-written member in these examples; reading another member reinterprets its stored representation and is not a portable way to recover the old value.
#include <stdio.h>
union Entry {
int count;
char grade;
};
int main(void) {
union Entry entry = {.count = 7};
printf("Count: %d\n", entry.count);
entry.grade = 'A';
printf("Grade: %c\n", entry.grade);
return 0;
}
Find the assignment that switches the stored member from count to grade. After that write, you cannot expect entry.count still to hold seven: the two members occupy overlapping storage.