5

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Hemanth
  • 5,035
  • 9
  • 41
  • 59

1 Answers1

7

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.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • 1
    What exactly are you quoting? It doesn't seem to be the C standard. – Lundin Jan 25 '11 at 12:27
  • 1
    @Lundin, I was quoting from the draft for the next standard. Added a note to my answer. – Jens Gustedt Jan 25 '11 at 12:29
  • That quote is in from the C1X draft . http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1516.pdf Some compilers supports this already. This feature comes from the Plan 9 C compiler btw. – nos Jan 25 '11 at 12:37
  • As far as I can tell from the current C99 standard, unnamed members are regarded as undefined behavior (6.7.2.1 §7). Have I interpreted that part of the standard correct? – Lundin Jan 25 '11 at 12:47
  • @Lundin, no I don't think so. I read this that it is only UB if none of the members is named. – Jens Gustedt Jan 25 '11 at 12:55
  • @Jens , so what is the use for such a anonymous structures and unions? we can directly have those inner_members as the member of one big outer structure right ? – Hemanth Jan 25 '11 at 13:25
  • Besides of the logical structuring of the the code, for anonymous structures in structures, the main interest is probably padding. For anonymous unions in structures this implements an overlay of the fields in question, so it really has an impact on the structure. Same holds for the other way round, anonymous structure inside a union. – Jens Gustedt Jan 25 '11 at 14:17
  • @Jens The inner struct isn't named, so it would count as an unnamed member of the larger struct? Also for the record I have encountered the same "avar->inner_mem1" case myself several times, but I am not sure if it is allowed by the standard. – Lundin Jan 25 '11 at 21:22