The error message is rather misleading. The behavior is compliant with the C++ standard certainly, but is inconvenient anyway. GCC allows the code.
Topics
About: C++
About: Visual C++
The table of contents of this article
- Starting Context
- Target Context
- Orientation
- Main Body
- 1: Encountering a "C2131: expression did not evaluate to a constant" Error
- 2: The Cause
- 3: The Solution
Starting Context
- The reader has a basic knowledge on C++.
Target Context
- The reader will know the real meaning of the "C2131: expression did not evaluate to a constant" error message and how to solve the problem.
Orientation
There are some more articles on Visual C++ peculiarities (an "unable to match function definition to an existing declaration" error, exporting the symbols from a DLL, explicitly instantiating constructor templates, a 'std::codecvt<char16_t,char,struct _Mbstatet>' unresolved error).
Main Body
Stage DirectionHypothesizer 7 soliloquies.
1: Encountering a "C2131: expression did not evaluate to a constant" Error
Hypothesizer 7
This code causes a compile error, "C2131: expression did not evaluate to a constant", for Visual C++ 2017, while it is good for GCC.
@C++ Source Code
void test2 (int const & a_arrayLength) {
int l_array [a_arrayLength];
}
2: The Cause
Hypothesizer 7
The error message is rather misleading: "did not evaluate to a constant"? It is constant, right?
Actually, the issue is not about not being constant in the C++ sense, but about not being compile-time-determined. . . . Why do we not straighten up the terminology more? C++ is somehow too lax in the terminology ("lvalue", "rvalue", "move semantics", "xvalue", "prvalue", "glvalue", "template instantiation", etc.).
The requirement that any stack array's length has to be compile-time-determined is compliant with the C++ standard actually, but is inconvenient nevertheless.
Considering the fact that GCC does not need such a requirement, do we really need such a requirement? . . . If someone says that it is for performance's sake, I am not convinced: I am not saying that any stack array's length should not be compile-time-determined; I am just wondering why should the programmer not be allowed to choose with his or her discretion. Allowing a compile-time-not-determined-length array will not have to slow down compile-time-determined-length arrays, will it?
3: The Solution
Hypothesizer 7
The only solution as far as I know is to use a heap array, which requires manually destroying it at an appropriate time.