Fedor
Fedor

Reputation: 21307

Can anonymous union be simply `const` (not `constexpr`)?

In the following example, an anonymous union declares member int i, which is injected in the enclosing scope, and const precedes the union declaration:

int main() {
    const union {
        int i = 0;
    };
    i = 1;
}

The compilers diverge in handling of this program.

MSVC accepts union declaration, but rejects i = 1 with the error:

error C3892: '$S1': you cannot assign to a variable that is const

GCC accepts the whole program without any warning, simply ignoring the const prefix.

Clang in -pedantic-errors mode issues the error:

anonymous union cannot be 'const' [-Werror,-Wpedantic]

Online demo

Which compiler is correct here?

Upvotes: 4

Views: 103

Answers (1)

Davis Herring
Davis Herring

Reputation: 40013

This is a known issue: the definition implies that no other decl-specifiers are allowed, contradicting the statements about storage class specifiers. (I’m not sure what the point of a const anonymous union would be anyway.)

Upvotes: 7

Related Questions