Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of a struct inside another without a tag name?

Tags:

c

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.

like image 699
Hemanth Avatar asked Jan 25 '11 12:01

Hemanth


People also ask

Can you define a structure without a name?

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.

How do you call a struct inside another struct?

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 .

What is a struct tag name?

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.

How do you use a struct inside a struct?

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.


1 Answers

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.

like image 162
Jens Gustedt Avatar answered Oct 05 '22 12:10

Jens Gustedt