Why doesn#39;t gcc allow a const int as a case expression?(为什么 gcc 不允许 const int 作为 case 表达式?)
问题描述
我正在查看这个 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 表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 gcc 不允许 const int 作为 case 表达式?
				
        
 
            
        基础教程推荐
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
 - Play 商店的设备兼容性问题 2022-01-01
 - iOS - UINavigationController 添加多个正确的项目? 2022-01-01
 - Android Volley - 如何动画图像加载? 2022-01-01
 - 如何将图像从一项活动发送到另一项活动? 2022-01-01
 - 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
 - 如何比较两个 NSDate:哪个是最近的? 2022-01-01
 - Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
 - UIImage 在开始时不适合 UIScrollView 2022-01-01
 - navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				