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循环中执行,无法跳出

  • 相关阅读:
    五星评价
    IE9以上 CSS文件因Mime类型不匹配而被忽略 其他浏览器及IE8以下显示正常
    js时间显示设置
    jq手风琴---点击时列表的左边距逐渐减小
    break continue return
    validate插件:验证密码没有空格 用户名是5-10位 至少包含数字和大小写字母中的两种字符
    Commons IO
    Servlet & JSP
    设计模式
    Table of Contents
  • 原文地址:https://www.cnblogs.com/encode/p/2964918.html
Copyright © 2011-2022 走看看