dimanche 9 juillet 2023

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?

Aucun commentaire:

Enregistrer un commentaire