Reputation: 95
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.
Upvotes: 2
Views: 3904
Reputation: 39
An “expected constant expression” error occurs when one tries to declare an arrays' size during runtime or during execution.
This happens because the compiler cannot; first, calculate the array size and then allocate that much space to the array.
A simple solution is to declare arrays with const int e.g array[45]
Another way to do it is to make a dynamic array :
int array_name = new int [size ];
Upvotes: -1
Reputation: 15872
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;
}
Note that this works on the oldest compiler I have access to at the moment (g++ 4.3.2).
Upvotes: 2
Reputation: 62472
If you're not using C++11 then use a std::vector :
std::vector<int> array_of_ints(int(a*b + 1));
This will cause the vector to pre-allocate the specified space and will initialize all the ints to zero.
Upvotes: 2
Reputation: 76240
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
.
Upvotes: 6