+ 1

Float Switch

I`m trying to use switch with float to compact a code but I can`t. Can someone explain if it was supposed to be this and explain why? Thanks.

4th Sep 2018, 1:25 PM
game_noob
game_noob - avatar
3 odpowiedzi
+ 6
C++ requires a switch to be of an integral type. e.g. char, short, int, long long. A float/double is a floating point so it's not accepted. A floating point is imprecise, for example 5.3f * 1.2f should be 6.36f. Yet 5.3f * 1.2f == 6.36f is false. A switch is converted to a binary search in assembly, or a lookup table ( an array ) depending on the cases. A lookup table cannot use floats as indexes A binary search requires a comparison using a subtraction. 2.33f - 0.33f, for example, is not equal to 2.f according to C++, so it cannot compare either. This is also the reason compilers warn you about floating comparisons.
4th Sep 2018, 1:50 PM
Dennis
Dennis - avatar
+ 3
You can not switch on a variable of type float. It is technically impossible for floats, because these numbers are not exact, whereas switch has the notion of exactly matching n different cases. https://stackoverflow.com/questions/7856136/java-inaccuracy-using-double
4th Sep 2018, 1:51 PM
Steppenwolf
Steppenwolf - avatar
+ 1
Sorry for the time I took to come back here but thank you both. :D
13th Nov 2018, 11:46 AM
game_noob
game_noob - avatar