7

Where can we use anonymous structs and unions?

struct
{
    int bar;
}; // anonymous struct

union
{
    int bar;
}; // anonymous union

I think that we can do it in the following standards:

  • unions - C++98, C++03, C++11, C11

  • structs - C11

Am i right or not

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 2
    gcc also supports anonymous unions in C99 as a GNU extension – Paul R Sep 10 '12 at 15:47
  • The style of the `struct` and `union` example you provided only makes sense if you place it in another `struct`/`union`. Is this the context you're talking about? – cha0site Sep 10 '12 at 15:52
  • 1
    @Paul R Yeah, i know, but i want to know what C and C++ standards says about it – FrozenHeart Sep 10 '12 at 15:56
  • Anonymous structs are not necessary in C++ because almost anything anonymous structs could be used for can be accomplished using inheritance. – ecatmur Sep 10 '12 at 16:26

1 Answers1

5

The statement about C is correct: the standardization of anonymous structs and unions is pretty new (C11) cfr. GCC man.

Note that your preferred compiler could enable those features as extensions to the current supported standard (e.g. GNU C99 extensions).

Then, checking old specs, it seems that anonymous unions are supported in C++ since 1998.

It is common knowledge that anonymous structs are forbidden in C++ and I did not find any amendment. As of Visual studio 2012, C++ is confirmed not supporting this feature.

ziu
  • 2,634
  • 2
  • 24
  • 39