简体   繁体   English

c ++:“期望的常量表达式”

[英]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? 我猜这是由于在编译时不知道int(a*b + 1)对吧? 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) ? 我的问题是:有什么办法可以编码上面的示例,以便它可以工作,并且array_of_ints大小为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): 将两个常量声明为constexpr (不幸的是,仅自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 . 另外(对于C ++ 11之前的C ++),您可以使用std::vector

If you're not using C++11 then use a std::vector : 如果您不使用C ++ 11,请使用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. 这将导致向量预先分配指定的空间,并将所有int初始化为零。

Declare a const int : 声明一个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). 请注意,这适用于目前我可以访问的最旧的编译器(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] 一个简单的解决方案是使用const int声明数组,例如array [45]
Another way to do it is to make a dynamic array : int array_name = new int [size ]; 另一种方法是创建一个动态数组:int array_name = new int [size];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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