Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression does not evaluate to a constant

Tags:

c++

I've just started to learn C++ and I don't understand this error:

std::string AFunction(const std::string& str) {
    size_t s = str.length();

    char inProgress[s];


    return std::string();
}

I get the error:

error C2131: expression does not evaluate to a constant

Here: char inProgress[s];

What do I have to do the set inProgress size with the length of str?

like image 301
VansFannel Avatar asked Oct 14 '25 14:10

VansFannel


1 Answers

The problem is that in standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program:

size_t s = str.length();
char inProgress[s]; //not standard C++ because s is not a constant expression

Better would be to use std::vector as shown below:

std::string AFunction(const std::string& str) {
    size_t s = str.length();

    std::vector<char> inProgress(s); //create vector of size `s`


    return std::string{};
}
like image 192
Anoop Rana Avatar answered Oct 17 '25 02:10

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!