void foo(const int size) {
char array[size];
}
int main() { }
The above code throws compiler error in Visual Studio C++:
error C2131: expression did not evaluate to a constant
note: failure was caused by a read of a variable outside its lifetime
Why is size not evaluated as constant even though it's declared as const int?
But the following code compiles successfully:
int main() {
const int size{ 10 };
char array[size];
}
const int sizejust means thatsizecan't be modified insidefoo, you can however pass any value you wish to it. For exampleint x; std::cin >> x; foo(x);would be totally legal.