简体   繁体   中英

Creating array with const int size parameter in a function throws error in Visual Studio C++: expression did not evaluate to a constant

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];
}

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.

数组的大小需要是一个编译时间常数,而不仅仅是运行时const

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.

Eg

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM