integer promotion

用小米的笔试题来举例吧

1 void fun()  
 2 {  
 3     unsigned int a = 2013;  
 4     int b = -2;  
 5     int c = 0;  
 6     while (a + b > 0)  
 7     {  
 8         a = a + b;  
 9         c++;  
10     }  
11     printf("%d", c);  
12 }  
问输出什么?

错误答案是1003,参考解释如下
If both operands have the same type, then no further conversion is needed.(废话)

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.(同为符号或同为无符号的整形,短整被提升为长整)

****此题目的关键就在此***
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.(当一个为符号型,另一个为无符号型且无符号型的范围更广时,都调整为无符号型,题目中a能表示到OXFFFFFFFF,而b最大到7FFFFFFF)

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.



此题明显调整为无符号型,而unsigned int的表示范围是0~4294967295,所以就看看a+b有不有可能为0就行了,很显然,a=2013,每次减2,当减到为1时,unisigned int(1-2)就不是-1了,而是4294967295(因为负数是按补码表示的,-1的补码为全1),所以这个函数一直在while循环中执行,无法跳出

原文链接: https://www.cnblogs.com/encode/archive/2013/03/17/2964918.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    integer promotion

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/80965

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午7:50
下一篇 2023年2月9日 下午7:50

相关推荐