简体   繁体   中英

Visual C++ Expression must have a constant value

Does anyone know why Visual Studio is the only compiler to giving me this error - Expression must have a constant value (referring to size).

#include <iostream>
#include <cstring>
using std::cout; using std::endl;

int main() {
    const char Ca3[] = { "Hello" };
    const char Ca4[] = { "World" };

    const size_t size = strlen(Ca3) + strlen(Ca4) + 2;

    char bigString[size];
    strcpy(bigString, Ca3);
    strcat(bigString, " ");
    strcat(bigString, Ca4);
    cout << bigString << endl;

    system("PAUSE");
    return 0;
}

The strlen function is not declared as constexpr , which means that the result of it is not a constant expression .

So size is not a constant expression and therefore it cannot be used as an array dimension. The code is ill-formed in Standard C++.

Many compilers have an extension that non-constant expressions may be used as an array dimension. If another compiler accepts this code then that would probably be the explanation. You might be able to prod the other compilers by using standards-compliance switches (eg for gcc, -std=c++14 -pedantic ).


To work around this you could write your own constexpr equivalent to strlen ; or you could use sizeof . Alternatively you could use std::string and avoid C-style string handling entirely.

The reason this is only happening with VC++ is that VC++ is (apparently) the only compiler you've tried that conforms to the C++ standard in this respect.

For some time, C has had a feature known as "variable length arrays", that would allow this. Some C++ compilers (especially gcc) also allow them in C++ (at least by default), even though the C++ standard prohibits them.

If you want something that acts like an array, but also allows you to specify its size at runtime, you usually want an std::vector instead of an array.

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