Tagged & Anonymous Unions
A raw union does not remember which member is active. A tag fixes that. An anonymous union removes one layer of names.
In plain English
A tagged union is a box with a label that says which item is inside.
Tagged unions
A tagged union combines a tag field with a union of alternatives. The tag says which member is currently valid, and the union stores the value. This pattern is the C ancestor of sum types. A union member can itself be a structure or an array; the tag then selects that entire representation. Always update the tag when you write a new member.
struct TaggedValue {
enum { INT, FLOAT } tag;
union {
int i;
float f;
} value;
};
struct TaggedValue v;
v.tag = INT;
v.value.i = 42;Anonymous unions and memory saving
An anonymous union has no member name, so its fields are accessed as if they belonged to the enclosing structure. This is convenient but can make the active field less obvious, so document the invariant. Unions save memory when only one of several representations is needed at a time, and they can model generic data types.
struct Packet {
int kind;
union {
int number;
char text[16];
}; /* anonymous union */
};
struct Packet p;
p.kind = 1;
p.number = 42;Structures and arrays inside a union
A union member can be a structure or an array. The union then stores one complete representation at a time, and the tag tells you which one is active. A union can also be a member of a structure, which is the usual way to attach a tag to the payload.
union Payload {
struct { int x, y; } point;
struct { char name[16]; } label;
char raw[16];
};
struct Variant {
enum { POINT, LABEL } tag;
union Payload value;
};
struct Variant v;
v.tag = POINT;
v.value.point.x = 3;
v.value.point.y = 4;Key takeaways
- A tag records which union member is active.
- A tagged union models alternatives safely.
- An anonymous union exposes its fields directly.
- Unions save memory when only one representation is needed.
- A union member can be a structure or an array; the tag selects the active representation.
Common pitfalls
- Forgetting to update the tag after writing a member.
- Reading an anonymous union field without checking the tag.
- Assuming a union is a generic type without a tag.
- Accessing the wrong structure member after changing the tag.
Key focus
- Know the structure of a tagged union.
- Expect questions on union memory savings.
- Be able to read a union containing a structure or an array.
Quick check
1. What is the purpose of the tag in a tagged union?
2. How do you access a member of an anonymous union inside a struct?