const variable not recognized as array dimension

狂风中的少年 提交于 2019-12-02 13:11:00

Array sizes must be known at compile time.

A const variable does not ensure that. The const qualifier ensures that the variable cannot be modified once it is initialized.

It is possible for the value of const variable to be known at compile time. If a compiler can detect that, then the variable can be used to define the size of an array.

More often, the value of a const variable is not known at compile time. It is initialized with a value at run time, which can't be changed after the variable is initialized. That does not make it fit for use to define the size of an array.

If you want to be able to use the variable at compile time, use constexpr instead. The compiler will do its best to evaluate the value at compile time. It will fail if the value of the variable cannot be evaluated at compile time.

The size N in an array declaration T[N] must be a compile-time constant-expression.

std::size_t const a{42}; // is one,

std::size_t foo{std::rand() % 100};
std::size_t const b{foo}; // is not, because it depends on foo

Marking something const does not make it a constant expression per se. It makes it a read only. The right hand side of your statement should satisfy constexpr function requirements, which the strlen(plainString) expression does not. You could make your own function that is evaluated during compile time:

constexpr size_t constexprlength(const char* s) {
    return strlen(s);
}

and use that instead:

constexpr size_t patternLength = constexprlength(plainString);
int partialMatch[patternLength];

VLAs and character arrays are evil. Use std::vector and std::string instead.

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