I found one code implemented as the similar demo shown below ..
struct st
{
int a;
struct
{
int b;
};
};
6.58 Unnamed struct/union
fields within structs/unions
As permitted by ISO C11
.
But What are benefits of it ?
Because anyway I can access the data members in a same manner like
int main()
{
struct st s;
s.a=11;
s.b=22;
return 0;
}
compiled on gcc 4.5.2 with ,
gcc -Wall demo.c -o demo
and no errors ,
In C11 standard of C, anonymous Unions and structures were added. Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions.
An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared.
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
The unions are basically used for memory saving & it's size is equal to the largest member of the union. And for accessing the data fields of a union, use the dot operator(.) just as you would for a structure and explained by @Atmocreations.
It does not have to be an anonymous struct inside a struct, which I do not find very useful: this will typically only change the layout slightly by introducing more padding, with no other visible effects (compared to inlining the members of the child struct into the parent struct).
I think that the advantage of anonymous struct/unions is elsewhere: they can be used to place an anonymous struct inside an union or an anonymous union inside a struct.
Example:
union u
{
int i;
struct { char b1; char b2; char b3; char b4; };
};
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