Visual C++ Expression must have a constant value

戏子无情 提交于 2021-01-20 06:56:41

问题


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

回答1:


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 (e.g. 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.




回答2:


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.



来源:https://stackoverflow.com/questions/35142294/visual-c-expression-must-have-a-constant-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!