C 中的 switch 语句:变量的情况?
#include <stdio.h>
int main(int argc, char *argv[]){
char a = 'c';
switch('c'){
case a:
printf("hi\n");
}
return 0;
}
对于此错误,上述内容将无法编译:
case label does not reduce to an integer constant
为什么不允许这样做?
#include <stdio.h>
int main(int argc, char *argv[]){
char a = 'c';
switch('c'){
case a:
printf("hi\n");
}
return 0;
}
The above won't compile for this error:
case label does not reduce to an integer constant
Why is this not allowed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
明确允许编译器使用高效的二叉树或跳转表来评估 case 语句。
因此,case 语句是编译时常量。
The compiler is explicitly allowed to use an efficient binary tree or a jump table to evaluate case statements.
For this reason, case statements are compile time constants.
想一想,如果您有以下内容怎么办:
它会返回什么?
大小写标签必须保持不变,以便编译器可以证明不存在歧义。
Think about, what if you had the following:
What would it return?
The case labels need to be constant so that the compiler can prove that there are no ambiguities.
switch
语句的想法是,编译器可以生成仅在运行时检查switch
表达式的代码,并由此推断出要跳转到的位置。如果
case
标签可能是非常量的表达式,则必须评估所有此类case
表达式以查看是否有匹配的表达式。因此,它必须计算n
个表达式,而不是计算一个表达式,其中n
是该switch 的
。case
标签数量switch
的整个想法是以与您相反的方式进行。将变化表达式a
放入switch
本身中,并将常量(如'c'
)放入 case 中。The idea of a
switch
statement is that the compiler can produce code that only inspects theswitch
expression at run time and by that deduces the location to jump to.If the
case
label could be expressions that are not constant, it would have to evaluate all suchcase
expressions to see if there is one that matches. So instead of evaluating one expression, it would have to evaluaten
expressions, wheren
is the number ofcase
labels for thatswitch
.The whole idea of the
switch
is to do it the other way round than you did. Put the varying expressiona
in theswitch
itself, and put constants such as your'c'
in the case.C99 标准是这么说的(C89 标准非常相似):
这就是语言要求:case 标签应为整数常量表达式,并且单个 switch 中的所有 case 都应是唯一的。这就是 C 的设计方式。现在不太可能更改(即使更改不会破坏任何当前有效的代码,甚至不会更改其含义)。
The C99 standard says this (and the C89 standard was very similar):
That's the language requirement: case labels shall be integer constant expressions, and all the cases in a single switch shall be unique. That is the way C was designed. It is very unlikely to change now (even though the change would not break any currently valid code, or even change its meaning).