Search code examples
c++c++11constantslanguage-lawyerunions

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?


Solution

  • 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.)