Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: "expected constant expression"

I am getting an "expected constant expression" error in the last line of the following code:

int main() {
    const float a = 0.5f;
    const float b = 2.0f;

    int array_of_ints[int(a*b + 1)];
}

I guess this is due to the fact that int(a*b + 1) is not known during compile time, right? My question is: Is there any way to code the above example so that it would work, and array_of_ints would have size int(a*b + 1)?

Any help or insight into what is going on here would be appreciated :)

Edit: I realize vector would solve this problem. However, I want the contents of the array to be on the stack.

like image 897
Dievser Avatar asked Feb 11 '26 23:02

Dievser


2 Answers

Declare the two constants as constexpr (unfortunately only available since C++11):

int main() {
    constexpr float a = 0.5f;
    constexpr float b = 2.0f;

    int array_of_ints[int(a*b + 1)];
}

Alternatively (for C++ prior to C+11) you can use an std::vector.

like image 149
Shoe Avatar answered Feb 13 '26 12:02

Shoe


Declare a const int:

int main() 
{
    const float a = 0.5f;
    const float b = 2.0f;
    const int s = static_cast<int>(a * b) + 1;

    int array_of_ints[s];
    return 0;
}

Example

Note that this works on the oldest compiler I have access to at the moment (g++ 4.3.2).

like image 33
Zac Howland Avatar answered Feb 13 '26 12:02

Zac Howland



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!