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?
A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).
Answer. Switch case variables can have only int and char data type. So float or no data type is allowed. In this ch can be integer or char and cannot be float or any other data type.
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
In switch case we can use only integer and character type data types.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With