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?
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
floatanddoubleis 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 thecasevalues.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.