why not 'switch case' accept float point in condition?

A switch case example as below. The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed. Why?

int main() 
{ 
   int x = 2; 
   switch (x) 
   { 
       case 1: printf("Choice is 1\n"); 
       case 2: printf("Choice is 2\n"); 
       case 3: printf("Choice is 3\n"); 
       default: printf("Choice other than 1, 2 and 3\n"); 
   } 
   return 0; 
}  

My best guess is it is because floating point values are inherently not precise. Switch statements are all about precise matching. Using real number types in a switch is potentially troublesome because in a computer, real numbers (floating point) are approximations (very precise approximations, but approximations nonetheless).

There are lots of articles out there which explain why comparing floats/doubles for exact equality is usually a mistake. Especially if the comparison is of the results of calculations. See for example:

Comparing Floating Point Numbers, 2012 Edition
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

Note the section: "Comparing for equality".


Floating point number representation
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html

Note the section:

"III. Effective FP Programming"

...

"Equality"

"First let's tackle that pesky issue of equality: why is it so hard to know when
two floats are equal?"


Why Floating-Point Numbers May Lose Precision
https://msdn.microsoft.com/en-us/library/c151dt3s.aspx

- Wayne

 

reference:

https://www.geeksforgeeks.org/interesting-facts-about-switch-statement-in-c/

https://social.msdn.microsoft.com/Forums/en-US/e3dc97a8-cd4b-4995-905e-0ab50060efe5/why-switch-case-cant-accept-floatingpoint-in-condition?forum=csharpgeneral

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章