Reputation: 32817
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]
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?
Upvotes: 7
Views: 5687
Reputation: 719346
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.)
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.
Upvotes: 16
Reputation: 182827
In the case of C++, it's because switch
/case
is not supposed to replicate the functionality of if
. If it's supposed to provide a way to get an efficient "jump table" in cases where the code permits it.
Upvotes: 6