为什么 switch case 语句中只允许有限的类型 [英] why only limited types allowed in switch case statements
问题描述
Java
、c++
、c
、c#
等语言允许 integral
类型或在 switch-case 语句中计算为整数类型的表达式.[string
文字和一些其他类型在某些语言中是允许的]
Languages like Java
,c++
,c
,c#
allow integral
type or an expression that evaluates to an integral type in switch-case statements.[string
literals and some other types are allowed in some languages]
为什么我们只需要使用 integral
类型或一些有限数量的类型而不是像 double
,float
这样的类型?是因为某种优化还是只是为了简单?
Why do we need to use only integral
types or some limited number of types and not types like double
,float
?Is it because of some kind of optimization or just for simplicity?
推荐答案
首先,Java 7 允许切换字符串值...... C# 也是如此.(在 Java 中,你不能打开long
...感谢你提醒我彼得.)
Firstly, Java 7 allows switching on String values ... and so does C#. (And in Java, you can't switch on a long
... thanks for reminding me Peter.)
然而,不允许打开 float
和 double
的原因很可能是舍入错误和浮点数的不精确表示的潜在影响会使代码使用浮点开关非常容易出错……或者需要特殊的语法来表达 case
值中的错误界限.
However, the reason that switching on float
and double
is not allowed is most likely that the insidious effects of rounding errors and imprecise representations of floating point numbers would make code that uses floating point switches very error prone ... or require a special syntax for expressing error bounds in the case
values.
现在,如果有很多很好的用例来切换浮点值,那么人们会期望某些语言会支持这一点.但据我所知,主流编程语言都没有沿着这条路走下去.
Now if there were lots of good use-cases for switching on floating point values, then one would expect that some language would support this. But to my knowledge no mainstream has programming language ever gone down this route.
这篇关于为什么 switch case 语句中只允许有限的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!