Why only restricted types are allowed in switch statements

Languages ​​such as Java , c++ , c , c# allow the integral type or expression, which evaluates the integral type in case statement statements. [ string literals and some other types 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

+7
source share
2 answers

First, Java 7 allows you to include String ... and C # values. (And in Java, you cannot enable long ... thanks for reminding me of Peter.)

However, the reason why the prohibition on including float and double unacceptable is most likely that the insidious effects of rounding errors and inaccurate representations of floating point numbers will make code that uses floating point very error prone. or special syntax is required to express error bounds in case values.

Now, if there were many good use cases for including floating point values, one would expect some language to support this. But, as far as I know, there is no programming language in the world that has ever followed this path.

+15
source

In the case of C ++, this is because switch / case should not replicate if functionality. If it is to provide a way to get an efficient "jump table" in cases where the code allows it.

+5
source

All Articles