Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why only limited types allowed in switch case statements

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?

like image 851
Anirudha Avatar asked Jan 14 '13 10:01

Anirudha


People also ask

Can switch-case handle all types of data?

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).

What are the limitations of switch-case statement?

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.

Which datatype is not allowed in switch-case?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

Which are the only data types that can be used with the switch conditions cases?

In switch case we can use only integer and character type data types.


1 Answers

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.

like image 132
Stephen C Avatar answered Oct 01 '22 23:10

Stephen C