3
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];
}
2
  • If you want a term to google, then the array size has to be a constant expression. Commented Feb 11, 2020 at 6:43
  • const int size just means that size can't be modified inside foo, you can however pass any value you wish to it. For example int x; std::cin >> x; foo(x); would be totally legal. Commented Feb 11, 2020 at 6:45

4 Answers 4

3

This compiles because size is truly constant.

int main() {
    const int size{ 10 };
    char array[size];
}

This however will not compile, because size is a constant variable, and not a compile time constant (there's a subtle difference)

void foo(const int size) {
    char array[size];
}

The reason it won't work, is because I can call foo with differing arguments.

foo(10);
foo(42);
foo(1);

The simplest work around is to use std::vector, which is what you are trying to do...

void foo(const int size) {
    std::vector<char> array(size);
}

and now 'array' will work with the same intent as your original code.

Sign up to request clarification or add additional context in comments.

Comments

2

C++ is a statically typed language and char array[1] and char array[2] are different types so those types must be known at compile time.

E.g

void foo(const int size) {
    char array[size];
}
int main() {
    int x = std::rand() % 1000;
    foo( x ); // Error
}

In this case, compiler cannot know the type of char array[size] at compile-time because the size is decided at run-time, so it is an error.

So as @Frodyne stated in comments, size of static arrays must be constant expression

Comments

2

The size of an array needs to be a compile time constant, not just run-time const.

Comments

-3

Since the constant variable size is initialized to '10', the value of the size cannot be modified. The size of the array is fixed and it cannot be changed.

int size = 10; // the value of the size can be changed.

1 Comment

The question is "Why is size not evaluated as constant even though it's declared as const int?" how does this answer the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.