zoukankan      html  css  js  c++  java
  • 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循环中执行,无法跳出

  • 相关阅读:
    ES5学习笔记
    React学习笔记一:入门知识概览
    《微服务架构与实践》学习笔记一:微服务架构理论
    Postgresql学习笔记
    玩转Bootstrap
    Python——XPath使用
    Python定向爬虫实战
    Python文本爬虫实战
    Python学习笔记九:正则表达式
    Python学习笔记八:ORM框架SQLAlchemy
  • 原文地址:https://www.cnblogs.com/encode/p/2964918.html
Copyright © 2011-2022 走看看