visual studio – Why compilers treat differently parenthesized type followed by an initializer list in C++?

The syntax (T){E1, E2, ...} where T is a type and E* are expressions is not valid standard C++ syntax. It is valid C though, where it is a so-called compound literal. Some compilers allow compound literals also in C++ code when not compiling in a strict standard-compliance mode (e.g. -pedantic-errors), but it is non-obvious how these compound literals behave in C++ context.

In particular, in GCC (and probably Clang as well), compound literals have different semantics in C++ code than in C code. Their lifetime and value category are different. See gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html.

So I suggest not using them, even if you only compile for compilers supporting them.

Your example can be easily rewritten in standard-conforming C++:

return std::array{
    "Zero",
    "One",
    "Two", 
}[val];

or pre-C++17:

return std::array{
    "Zero",
    "One",
    "Two", 
}[val];

Read more here: Source link