简体   繁体   中英

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.

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 .

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.

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).

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 eg array[45]
Another way to do it is to make a dynamic array : int array_name = new int [size ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM