Anonymous sub-structures and GCC
[example trimmed for simplicity -- rgs]
Quote:
>typedef struct
>{
> union
> {
> int x;
> long y;
> };
>} my_struct;
>void my_func(void)
>{
> my_struct str1;
> str1.x = 0;
>}
>Now for my questions:
>Is this legal?
No. The declaration of the union inside the structure is legal, but
useless -- you don't create anything of that union type and you don't give
the union type a tag, so you can't refer to it later.
However, the reference to str1.x is not legal simply because x is not a
member of str1. It's a member of the union type declared inside my_struct,
but that's a quite different thing. This is analogous to doing
void bar(void)
{
union {
int foo;
};
foo = 42;
}
which is obviously not legal.
Quote:
>(Micro$oft manages to compile it, as do a few others I have tried)
Yes, there is a Microsoft-specific extension which allows this. It just
promotes the members of the enclosed struct or union to be members of the
enclosing one. This is duly flagged as an MS extension in the online help.
Quote:
>How can I make GCC compile it?
Fix the broken code! :-)
Quote:
> I get a warning in the declaration (anonymous struct/union declares no
instances)
Right, this is warning you that the enclosed union type declaration is
useless: it has no tag (it's anonymous) and you don't declare anything with
that type.
Quote:
> I get an error when I try to use it (my_struct doesnt contain an element
'x')
Right, it doesn't contain an element 'x' as explained above.
Maybe you wanted to do this:
Quote:
>typedef struct
>{
> union
> {
> int x;
> long y;
> } z;
>} my_struct;
>void my_func(void)
>{
> my_struct str1;
> str1.z.x = 0;
>}
Now you've created something, 'z', of this union type and embedded it as a
member of the struct. str1 therefore has a member z, which is of union type
and in turn has a member x -- so the whole thing can be referred to as
str1.z.x. Of course, this works for str1.z.y as well. This may give you
the effect you wanted (depending on exactly what you were trying to do).
Cheers,
Richard