Anonymous unions inside structs
What you'll learn: How to nest a union inside a struct without a name to create cleaner, more intuitive data structures.
The "Multiplex" pattern
In C, a struct often needs to store different types of data depending on the situation. For example, a Message struct might contain a string of text OR a set of coordinates, but never both at the same time.
Normally, nesting a union requires giving it a name, leading to clunky access like msg.data.text. An anonymous union allows you to skip that middle name. It maps multiple variables to the same memory location directly inside the struct, making your code feel like it has "flexible" fields.
Clean access with anonymous unions
Think of a standard struct like a dresser where every drawer has a specific label. An anonymous union is like having one "magic drawer" that changes its internal layout depending on what you need to put in it. You don't have to open a "Union Box" inside the drawer; you just reach into the drawer and grab what you need.
By omitting the tag and variable name for the internal union, the members are "hoisted" into the scope of the parent struct.
#include <stdio.h>
struct Packet {
int type; // 0 for ID, 1 for Coordinate
// Anonymous union: no name between the '}' and ';'
union {
int id_number;
float coordinate;
};
};
int main() {
struct Packet p;
p.type = 1;
p.coordinate = 42.5f;
// Notice we don't say p.data.id_number.
// We access it directly as if it were a normal struct member.
printf("Type: %d, Value: %.1f\n", p.type, p.coordinate);
return 0;
}
Why use this?
- Readability: Your code is less verbose.
player.xis easier to read thanplayer.pos.x. - Memory Efficiency: You get the space-saving benefits of a union (where members overlap in memory) without the syntactical baggage of extra names.
- Logic: It is perfect for "Variant" types, where a struct has a
typeflag that tells you which part of the anonymous union is currently valid to read.
Key takeaway
Anonymous unions let you nest overlapping fields inside a struct so you can access them directly by name, keeping your syntax clean while saving memory.