Reputation: 5145
I just came across a code snippet say:-
struct a {
int mem1;
char mem2;
struct {
int inner_mem1;
int inner_mem2;
};
};
And I found that the code snippet using the inner struct's members directly using the outer struct's variable name!!! ex:
struct a *avar;
....
avar->inner_mem1
Is this legal, the code is compiling however and working fine!. What is the purpose to use it in this way? Any specific scenarios ?
Please let me know your thoughts.
Upvotes: 5
Views: 1453
Reputation: 79003
This is called an "anonymous structure":
An unnamed member of structure type with no tag is called an anonymous structure; an unnamed member of union type with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.
This is not part of the current C standard, C99, but it is foreseen to be part of the upcoming one (citation above). Also, many compilers already support this feature as an extension.
Upvotes: 7