9.1 Unions
A union lets several members share one block of memory. You can think of it as one storage slot that can be interpreted as different types, but only the most recently written member is reliable at a given moment.
c
union Value {
int int_value;
double double_value;
char letter;
};
union Value v;
v.int_value = 42; // int_value is the member to read now
v.double_value = 3.14; // overwrites the same memory; int_value is no longer reliableA union's size is usually the size of its largest member, because every member starts at the same address. A struct gives each member its own place; that is the next section.
Track the Current Type with a Tag
A union does not remember which member is currently stored. A common pattern is to keep an enum tag beside it:
c
enum ValueKind { VALUE_INT, VALUE_DOUBLE };
enum ValueKind kind = VALUE_INT;
union Value v;
v.int_value = 42;
if (kind == VALUE_INT) {
printf("%d\n", v.int_value);
}Update the tag and the union together. Otherwise, the program may read the same bytes as the wrong type and get a meaningless result.
Loading interactive lab...
Loading concept check...
Loading practice...