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

本文探讨了C语言中switch-case语句为什么只接受整型表达式作为条件判断的原因。主要原因是浮点数在计算机中是近似值,无法精确匹配,这可能导致在比较时出现意料之外的结果。文章引用了多个权威来源,详细解释了浮点数的表示和比较为何复杂。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值