A Tag Tells You What Is Stored
Keep track of which member is stored
A union doesn't record which member you wrote last. A separate kind value can do that job. An enum introduces names for integer choices: here TOOL_COUNT is 0 and QUALITY_GRADE is 1. enum Kind kind stores one such choice. We will return to enums in the Named Types section.
Here a struct holds both the tag and the union. The tag describes how to interpret the shared storage; it does not occupy that storage or change the union's layout. The program checks the tag before choosing a member to print.
#include <stdio.h>
enum Kind {
TOOL_COUNT,
QUALITY_GRADE
};
struct Ticket {
enum Kind kind;
union {
int count;
char grade;
} value;
};
int main(void) {
struct Ticket ticket = {.kind = TOOL_COUNT, .value.count = 4};
if (ticket.kind == TOOL_COUNT) {
printf("Tools: %d\n", ticket.value.count);
} else {
printf("Grade: %c\n", ticket.value.grade);
}
return 0;
}
The nested union has no type name, but its member inside Ticket is named value. Read ticket.value.count in two steps: select the value union, then its count member. The initializer uses .value.count = 4 to select that same nested member.
Run and check Tools: 4. For a grade ticket, both initializer entries would need to change to .kind = QUALITY_GRADE and .value.grade = 'A'. C does not keep the tag and union synchronized for you. A mismatched tag makes the branch select the wrong member.