随笔-19  评论-19  文章-17  trackbacks-0

数据升级 int 和 unsigned int

运行下面代码:
#include <stdio.h>
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int array[] = 32,33,11,42,43,21 };

int main()
{
    
int d = -1;

    
if ( d <= TOTAL_ELEMENTS - 2 )
        printf(
"d is less than TOTAL_ELEMENTS-2)  ;
    else
        printf(
"d is NOT than TOTAL_ELEMENTS-2)  ;
       
    
return 0;
}

看看运行结果输出是什么?

原因:
        C中的整数升级: char, short int 或者int型位段,包括他们的有符号和无符号变型,以及枚举类型,可以使用在需要int 或 unsigned int 的表达式中。如果int能完整表示源类型的所有值,那么该源类型的值就被转换成int,否则转换成unsighed int。

        sizeof()返回的是unsigned int, 当 d 与 TOTAL_ELEMENTS - 2 比较时会升级为unsigned int,  因为d是-1就被转成了一个非常大的正数

         需将 if ( d <= TOTAL_ELEMENTS - 2 ) 改成 if ( d <= (int)TOTAL_ELEMENTS - 2 )

建议: 在代码中尽量少使用无符号类型,特别不要因为有些年龄,人口等无负数的值,而使用无符号类型。
posted on 2005-08-31 21:24 我在等待 阅读(206) 评论(0)  编辑 收藏
昵称:我在等待
园龄:6年10个月
粉丝:0
关注:0
<2012年2月>
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

搜索

 
 

常用链接

随笔档案

文章分类

RSS related

最新评论

阅读排行榜

评论排行榜

推荐排行榜