Are “anonymous structs” standard? And, really, what *are* they?

All the standard text refers to creating an “unnamed struct”:

struct {
   int hi;
   int bye;
};

Just a nice friendly type, with no accessible name.

In a standard way, it could be instantiated as a member like this:

struct Foo {
   struct {
      int hi;
      int bye;
   } bar;
};

int main()
{
   Foo f;
   f.bar.hi = 3;
}

But an “anonymous struct” is subtly different — it’s the combination of an “unnamed struct” and the fact that you magically get members out of it in the parent object:

struct Foo {
   struct {
      int hi;
      int bye;
   }; // <--- no member name!
};

int main()
{
   Foo f;
   f.hi = 3;
}

Converse to intuition, this does not merely create an unnamed struct that’s nested witin Foo, but also automatically gives you an “anonymous member” of sorts which makes the members accessible within the parent object.

It is this functionality that is non-standard. GCC does support it, and so does Visual C++. Windows API headers make use of this feature by default, but you can specify that you don’t want it by adding #define NONAMELESSUNION before including the Windows header files.

Compare with the standard functionality of “anonymous unions” which do a similar thing:

struct Foo {
   union {
      int hi;
      int bye;
   }; // <--- no member name!
};

int main()
{
   Foo f;
   f.hi = 3;
}

It appears that, though the term “unnamed” refers to the type (i.e. “the class” or “the struct”) itself, the term “anonymous” refers instead to the actual instantiated member (using an older meaning of “the struct” that’s closer to “an object of some structy type”). This was likely the root of your initial confusion.

Leave a Comment