0

I have some C code and using the GCC compiler.

The code has some nested types inside an anonymous union:

struct ab {
    int a;
    int b;
    union {
        int *c;
        int *d;
        struct f {
           int *c;
           int *d;
        };
        struct e {
            int *c;
            int *d;
        };
    };
};

I am getting this error:

Error: 'struct ab::<anonymous union>::f' invalid; an anonymous union 
can only have non-static data members.

Can someone give further explanation why this error is happening?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
sachin
  • 23
  • 1
  • 2
  • You're getting an error because this makes no sense. It is not clear from your question what you expect this to do, but if you add that, someone can answer how you can achieve that. –  Jul 14 '13 at 07:25
  • 3
    § 9.5/5 - *The member-specification of an anonymous union shall only define non-static data members. [ Note: Nested types and functions cannot be declared within an anonymous union. — end note ]* – chris Jul 14 '13 at 07:27
  • The questions is not clear, be precise. – Ankit Zalani Jul 14 '13 at 07:39

3 Answers3

5

Well, you are not allowed to declare nested types inside anonymous unions. And that is exactly what you did: you declared classes f and e inside your anonymous union. This is what the compiler does not like. It is telling you that all you can do inside anonymous union is declare non-static data members. You can't declare nested types there.

It is not clear what you are trying to to here, so it is hard to offer any further suggestions.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
4

Remove your definition for struct inside the union.

struct ab {
    int a;
    int b;
    union {
        int *c;
        int *d;
        struct  {
           int *c;
           int *d;
        };
        struct {
            int *c;
            int *d;
        };
    };
};
0

When referencing the union member, it acts like a struct member. You have created an ambiguous situation for the compiler.

Here is more information on the GCC specifications: http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields

How to compile C code with anonymous structs / unions?

Community
  • 1
  • 1
lulyon
  • 6,707
  • 7
  • 32
  • 49