我正在使用 MinGW GNU 编译器编写 C++,当我尝试使用外部定义的整数变量作为 switch 语句中的 case 时出现问题。我收到以下编译器错误:“case label does not reduce to an integer constant”。
因为我已经将整数变量定义为 extern 我相信它应该可以编译,有人知道问题出在哪里吗?
下面是一个例子:
测试.cpp
#include <iostream>
#include "x_def.h"
int main()
{
std::cout << "Main Entered" << std::endl;
switch(0)
{
case test_int:
std::cout << "Case X" << std::endl;
break;
default:
std::cout << "Case Default" << std::endl;
break;
}
return 0;
}
x_def.h
extern const int test_int;
x_def.cpp
const int test_int = 0;
此代码将在 Visual C++ 2008 上正确编译。此外,我的一位蒙大拿 friend 检查了 ISO C++ 标准,似乎任何 const-integer 表达式都应该有效。这可能是编译器错误还是我错过了一些明显的东西?
这是我的编译器版本信息:
Reading specs from C:/MinGW/bin/../lib/gcc/mingw32/3.4.5/specs
Configured with: ../gcc-3.4.5-20060117-3/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug
Thread model: win32
gcc version 3.4.5 (mingw-vista special r3)
最佳答案
case
标签需要一个整数常量表达式,它有严格的要求,可以在编译时在使用时确定它们的值。
从 5.19 [expr.const] 开始,“整型常量表达式 只能包含文字 (2.13)、枚举数、const 变量或整型或枚举类型的静态数据成员使用常量初始化表达式 (8.5),...".
在需要常量表达式的地方使用 test_int
时,它是一个声明为 extern
且没有任何初始化程序的 const
变量并且不满足常量表达式的要求,尽管事实上您确实在另一个翻译单元中使用整数常量表达式对其进行了初始化。 (*从标准的措辞来看,这并不完全清楚,但这是我目前对它的解释。)
标准中的限制不允许这样的用法:
void f(int a, int b)
{
const int c = b;
switch (a)
{
case c:
//...
}
}
在您的示例中,当编译器编译 test.cpp
时,它无法确定 x_def.cpp
中的初始化器可能是什么。你可能做过:
const int test_int = (int)time();
显然,在这两个示例中,const int
的值都不能在编译时确定,而这正是整数常量表达式的意图。
关于C++ Switch不会使用用作大小写的外部定义变量进行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1869970/