Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1071307
  • 博文数量: 646
  • 博客积分: 288
  • 博客等级: 二等列兵
  • 技术积分: 5375
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-08 14:33
个人简介

为了技术,我不会停下学习的脚步,我相信我还能走二十年。

文章分类

全部博文(646)

文章存档

2014年(8)

2013年(134)

2012年(504)

分类:

2012-08-28 20:49:52

本文的copyleft归gfree.wind@gmail.com所有,使用GPL发布,可以自由拷贝,转载。但转载请保持文档的完整性,注明原作者及原链接,严禁用于任何商业用途。
作者:gfree.wind@gmail.com
博客:linuxfocus.blog.chinaunix.net
 

前几天看C99标准,写了两篇关于整数提升的博文,http://blog.chinaunix.net/space.php?uid=23629988&do=blog&id=2938697在这篇的评论中,pragma朋友提出了一个问题。经过了重新阅读C99,和别人讨论,外加思考,得到了答案。这再次加深了我对整数提升的理解,所以需要进一步总结一下这个问题。

先看看pragma提出的问题吧。
  1. #include <stdlib.h>
  2. #include <stdio.h>


  3. #define PRINT_COMPARE_RESULT(a, b) \
  4.     if (a > b) { \
  5.         printf( #a " > " #b "\n"); \
  6.     } \
  7.     else if (a < b) { \
  8.         printf( #a " < " #b "\n"); \
  9.     } \
  10.     else { \
  11.         printf( #a " = " #b "\n" ); \
  12.     }

  13. int main()
  14. {
  15.     signed int a = -1;
  16.     unsigned int b = 2;
  17.     signed short c = -1;
  18.     unsigned short d = 2;

  19.     PRINT_COMPARE_RESULT(a,b);
  20.     PRINT_COMPARE_RESULT(c,d);

  21.     return 0;
  22. }
输出结果为
  1. [root@Lnx99 test]#./a.out
  2. a > b
  3. c < d
为什么将int换为short后,结果就不一样了呢?

在C99标准中算数运算中有两种conversion,一个是integer promotion,另外一个是usual arithmetic conversions。在前面的博文中,我研究的是第二种,并将其理解为integer promotion,其实是不准确的。

下面是C99中关于第一种integer promotion的描述:
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.
——在C99的上下文,这个integer promotion发生在算术运算的时候。

而C99关于usual arithmetic conversions,参加我这篇博文:
http://blog.chinaunix.net/space.php?uid=23629988&do=blog&id=2938697

这样的话,也就是说在算术运算中,会涉及两种integer conversion。上面的测试代码的结果,也是由此而来。

下面开始分析:
对于a和b来说,integer promotion相当于不起作用,所以只进行usual arithmetic conversion,根据规则,将a转为unsigned int,所以a>b。
对于c和d来说,首先integer promotion会起作用,c和d都会转为int型,也就是说相当于int c = -1,int d = 2;然后进行usual arithmetic conversion,因为两者此时都为int型,那么自然结果是c < d了。


现在答案已经清晰了,但是却让我感到一阵阵忐忑,因为这样的整数转换规则太容易让人犯错了。对于我们来说,虽然已经比较明晰两个规则,但是在代码中还是要尽量避免有符号数和无符号数的比较。如果无法避免,为了清楚的表明自己的目的,最好使用强制类型转换。
阅读(361) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~