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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With