A nameless union
inside a struct
makes sense because it allows you to refer to the members of the union without specifying its name, hence shorter code:
struct {
int a;
union {
int b, c, d;
};
} foo;
So accessing the members of the union
is just like accessing a member of the containing struct: foo.a
and foo.b
. Otherwise you have to use foo.union_name.b
to access a member of the union.
Of course a "user" programmer using such a struct should be aware that setting foo.c
affects the value of foo.b
and foo.d
.
For the same reason the reverse can be done, namely putting an anonymous struct
inside a union
:
union {
struct {
int a, b;
};
int c;
} foo;
This way foo.a
and foo.b
can be used simultaneously and foo.c
can be used in another case.
I can't think of any other uses for anonymous structs or unions. "Declaring" an anonymous struct/union is an oxymoron and is just like saying int;
instead of int a;
.