变量不能出现在恒定表达(Variable cannot appear in a constant-e

2019-09-29 11:21发布

我有一个很难搞清楚为什么GCC 4.5不让我编译这个:

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
    const unsigned int length = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));

    std::bitset<length> bits;

    return 0;
}

它工作得很好,在VS2010。 我在想什么?

更新:我很着急,我没有粘贴整个代码。 对于那个很抱歉 :(

PS:正如标题所说,我收到的错误是:“长度不能出现在一个常数表达式。”

Answer 1:

我不知道你是否遇到的问题是由错误的编译器造成的,或者说是预期的行为,而只是移除的static_cast浮动似乎解决了问题,并在值完全相同的结果。

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
    const unsigned int length_1 = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));
    const unsigned int length_2 = static_cast<const unsigned int>(CEIL_POS(WIDTH * HEIGHT / 8.0));

    std::cout << length_1 << '\n' << length_2 << '\n';
    if (length_1 == length_2)
        std::cout << "They are exactly the same.";

    std::bitset<length_2> bits;
}


文章来源: Variable cannot appear in a constant-expression