I can see how
union {
uint32_t ip_address
struct {
uint8_t oct1;
uint8_t oct2;
uint8_t oct3;
uint8_t oct4;
};
};
Might be of some use to someone, but struct in a struct example here: Detail of MS warning C4201 seems a bit odd. Can anyone demonstrate a good usage case?
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;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With