Why does C++ disallow anonymous structs?

Adrian McCarthy picture Adrian McCarthy · Feb 12, 2010 · Viewed 58.1k times · Source

Some C++ compilers permit anonymous unions and structs as an extension to standard C++. It's a bit of syntactic sugar that's occasionally very helpful.

What's the rationale that prevents this from being part of the standard? Is there a technical roadblock? A philosophical one? Or just not enough of a need to justify it?

Here's a sample of what I'm talking about:

struct vector3 {
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float v[3];
  };
};

My compiler will accept this, but it warns that "nameless struct/union" is a non-standard extension to C++.

Answer

bames53 picture bames53 · Oct 8, 2012

As others have pointed out anonymous unions are permitted in standard C++, but anonymous structs are not.

The reason for this is that C supports anonymous unions but not anonymous structs*, so C++ supports the former for compatibility but not the latter because it's not needed for compatibility.

Furthermore, there's not much use to anonymous structs in C++. The use you demonstrate, to have a struct containing three floats which can be referred to either by .v[i], or .x, .y, and .z, I believe results in undefined behavior in C++. C++ does not allow you to write to one member of a union, say .v[1], and then read from another member, say .y. Although code that does this is not uncommon it is not actually well defined.

C++'s facilities for user-defined types provide alternative solutions. For example:

struct vector3 {
  float v[3];
  float &operator[] (int i) { return v[i]; }
  float &x() { return v[0]; }
  float &y() { return v[1]; }
  float &z() { return v[2]; }
};

* C11 apparently adds anonymous structs, so a future revision to C++ may add them.