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.
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. Definition is just like that of a normal union just without a name or tag.
You need to give it a name. Let's say b : struct A { int data; B b; }; To do that, the compiler needs to already know what B is, so declare that struct before you declare A .
An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type. A variable of that structure type holds the entire sequence defined by that type. Structures in C are similar to the types known as "records" in other languages.
One can't declare structure variable of type struct Employee anywhere else in the program. Cannot be used in multiple data structures: The nested structure cannot be used in multiple structures due to the limitation of declaring structure variables within the main structure.
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.
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