C++ Switch不会使用用作大小写的外部定义变量进行编译

标签 c++ gnu

我正在使用 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/

相关文章:

c++ - C++ 获取基类指针的方法

c++ - 为什么这段代码不能正常打印数字?

linux - 如何创建可在 32 位和 64 位 Linux 上运行的可执行文件?它与SYSV 和GNU/Linux 格式有关吗?

c++ - inFile 应该放在 -o 标志之前还是之后?

c++ - PCL 云法线在简单测试用例中的不确定性

c++ - 如何在2条正弦曲线之间绘制表面

C++ 调用多个构造函数

linux - shell脚本中特定行结尾的命令未找到错误

assembly - 如何防止 GNU ld 对目标文件重新排序?

linux - 在末尾添加摘要的问题/失败数量的计数器