我正在查看这个 SO 问题并开始考虑 constints 与 #defines 并意识到我实际上并不明白为什么编译器不能处理这个问题.有人可以解释一下为什么下面的代码
I was looking at this SO question and got to thinking about const ints versus #defines and realized I don't actually understand why the compiler can't deal with this. Could someone shed some light as to why the following code
const int FOO = 10;
int main(int argc, char** argv)
{
switch(argc)
{
case FOO: { printf("foo
"); }
default: { printf("default
"); }
}
}
结果
error: case label does not reduce to an integer constant
我阅读了 6.8.4.2.3 中规定的 ISO-C99 规范
I read the ISO-C99 spec which states in 6.8.4.2.3 that
每个case标签的表达应该是一个整数常量表达和没有两种情况相同的常量表达式switch 语句应具有相同的转化后的价值.
The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion.
我明白为什么 case 表达式必须是常量,但不明白为什么只有文字才能让编译器 (gcc 4.2.1) 满意.
I understand why the case expression must be constant, but not why only a literal makes the compiler (gcc 4.2.1) happy.
常量表达式与 const 限定的类型值不同,尽管从技术上讲,编译器在 处知道该值case
语句.
A constant expression is not the same as a const-qualified type value, even though technically the value is known by the compiler at the point of the case
statement.
想象一下,如果另一个文件声明 extern const int FOO
并尝试以相同的方式使用它会发生什么.编译器不知道 FOO
是什么,因为它是在另一个文件中定义的.即使它有一个常量值,它也不是一个常量表达式.
Imagine what would happen if another file declared extern const int FOO
and tried to use it the same way. The compiler wouldn't know what FOO
was because it was defined in another file. Even though it has a constant value, it is not a constant expression.
这篇关于为什么 gcc 不允许 const int 作为 case 表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!