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

  • 相关阅读:
    java 基础笔记 基本数据类型对象包装类
    java String 类 基础笔记
    java 线程 笔记 基础
    java 线程 基础笔记2
    java 异常学习 笔记
    广告简单概念整理-持续更新
    curl一些使用技巧
    简单学习正则表达式
    Linux命令简单操作之lsof
    Linux命令简单操作之find和xargs
  • 原文地址:https://www.cnblogs.com/encode/p/2964918.html
Copyright © 2011-2022 走看看