-3

Is it legal to have fields with the same name across different anonymous structures inside one union?

union Foo
{
    struct
    {
        int bar;
    };

    struct
    {
        int bar;
    };
};

MSVC does in fact allow this while GCC doesn't.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 4
    Your use-case for doing this is - what? –  Nov 14 '18 at 22:17
  • 1
    @Neil Butterworth It was actually made by an accident as the real example is much bigger and more complex than the one I've provided here – FrozenHeart Nov 14 '18 at 22:20
  • Possible duplicate of [Are "anonymous structs" standard? And, really, what \*are\* they?](https://stackoverflow.com/questions/14248044/are-anonymous-structs-standard-and-really-what-are-they) – Swordfish Nov 14 '18 at 22:24
  • Possible duplicate of [Anonymous union and struct](https://stackoverflow.com/questions/25542390/anonymous-union-and-struct) – Swordfish Nov 14 '18 at 22:25
  • Disable language extensions of `cl` (`/Za`) and get: `error C2467: illegal declaration of anonymous 'struct'` and `error C2658: 'Foo::bar': redefinition in anonymous struct/union`. – Swordfish Nov 14 '18 at 22:50

1 Answers1

4

The code is not valid, simply because C++ has no anonymous structures.

With -pedantic-errors, GCC refuses to compile it with error: ISO C++ prohibits anonymous structs [-Wpedantic].

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • I've just updated my question, please take a look at the new version. – FrozenHeart Nov 14 '18 at 22:29
  • @FrozenHeart I'd say it warrants a separate question, probably tagged `language-lawyer`. But since both GCC and Clang reject the new snippet as well, I smell MSVC bug. – HolyBlackCat Nov 14 '18 at 22:34