为什么 switch case 语句中只允许有限的类型 [英] why only limited types allowed in switch case statements

查看:35
本文介绍了为什么 switch case 语句中只允许有限的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javac++cc# 等语言允许 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.)

然而,不允许打开 floatdouble 的原因很可能是舍入错误和浮点数的不精确表示的潜在影响会使代码使用浮点开关非常容易出错……或者需要特殊的语法来表达 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆