Note: There are a number of questions on Stack Overflow with very similar-looking titles, but none that I have found is actually a duplicate, IMHO.
I have been using code like the following in my project(s) for a number of years, without problem. However, since a recent update to Visual Studio 2019 (16.7.2 - though it may have been at 16.7.1), the MSVC compiler has started to generate the error shown (I have the compilation 'Standard' set to C++17).
#include <iostream>
class Foo {
public:
Foo() { }
static constexpr char Letters[6][10] = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot" };
};
int main()
{
Foo f;
for (int i = 0; i < 6; ++i) std::cout << f.Letters[i] << std::endl;
return 0;
}
Error (at the opening brace in the constexpr
line):
error C2131: expression did not evaluate to a constant
message : failure was caused by a read of an uninitialized symbol
The clang-cl compiler continues to accept the code without any warning.
I have a fairly 'trivial' fix for this issue, as below:
class Foo {
public:
Foo() { }
inline static const char Letters[6][10] = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot" };
};
However, I am intrigued by the error report. Is there something I am missing (and have been missing for ~5 years), or is this a bug in the latest release of MSVC? If the former, what is my error or invalid assumption?
Your code is valid (and accepted by GCC and Clang), and this is indeed a bug in MSVC v 19.27 and above. Online demo: https://gcc.godbolt.org/z/rdnn9M8j3
The bug was reported on January 26, 2021: https://developercommunity.visualstudio.com/t/Compile-error--when-declare-static-const/1320740 and is currently under investigation.