Fields with the same name across different anonymous unions inside one union
Asked Answered
A

1

5

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

union Foo
{
    union
    {
        int bar;
    };

    union
    {
        int bar;
    };
};

This code fails to compile by GCC but works fine in MSVC.

Auberge answered 14/11, 2018 at 22:38 Comment(2)
It looks like this is not allowed: "Members of an anonymous union are injected in the enclosing scope (and must not conflict with other names declared there)" en.cppreference.com/w/cpp/language/union#Anonymous_unionsMongeau
It is a language extension of cl. Disable language extensions (/Za) and happily get: error C2658: 'Foo::bar': redefinition in anonymous struct/unionStomatic
C
9

This is not allowed by C++ standard. Any compiler which compiles this code is non-conformant.

See 10.4.1/1:

The names of the members of an anonymous union shall be distinct from the names of any other entity in the scope in which the anonymous union is declared.

Cotsen answered 14/11, 2018 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.