关于开关{}情况下用C? [英] About switch{} case in C?
问题描述
我读 C语言
一些文字。文说,开关{}情况下
只能接受整型。
I am reading some text in C language
. The text says that switch{} case
can only accept integer type.
我只是好奇,为什么开关{}情况下
不接受其他类型的如float或字符串。在这背后有什么原因呢?
I am just curious about why switch{} case
does not accept other types such as float or string. Are there any reasons behind this?
非常感谢。
推荐答案
经典的原因可能是对整数值的决定前pressions,这是可以做到非常好的优化。
The classical reason is probably that for integer-valued "decision expressions", it's possible to do very nice optimizations.
基本上,你可以区分语句列表映射到包含地址的表,然后直接跳到基础上的价值。显然,对于花车和字符串不起作用。
Basically, you can map the list of case-statements to a table containing addresses, and then directly jump based on the value. Obviously, for floats and strings that doesn't work.
在GCC,你可以手工使用一些扩展像这样:
In GCC, you can do this by hand using some extensions like so:
const char * digit_name(int d)
{
const void * handlers[] = { &&zero, &&one, &&two, &&three, &&four,
&&five, &&six, &&seven, &&eight, &&nine };
goto *handlers[d]; /* Assumes d is in range 0..9. */
zero: return "zero";
one: return "one";
two: return "two";
three: return "three";
four: return "four";
five: return "five";
six: return "six";
seven: return "seven";
eight: return "eight";
nine: return "nine";
return NULL;
}
这是一般称为计算GOTO,它应该清楚如何开关
基本上可以编译成非常类似的东西。在接通前pression的紧密定义有所帮助,如使用枚举
。
This is in general called a "computed goto", and it should be clear how a switch
can basically be compiled down to something very similar. Tight definition of the switched-on expression helps, such as using an enum
.
此外,C并没有真正有多少串的概念在语言级别。
Also, C doesn't really have much of a concept of strings at the language level.
这篇关于关于开关{}情况下用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!