有如下两个程序:
程序一:
#include <stdio.h>
int array[] = {23, 34, 12, 17, 204, 99, 16};
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int main() {
int d = -1,x;
x = 0;
if (d <= TOTAL_ELEMENTS - 2)
x = array[d+1];
printf("%d/n", x);
return 0;
}
程序二:
#include <stdio.h>
int array[] = {23, 34, 12, 17, 204, 99, 16};
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int main() {
int d = -1,x;
x = 0;
if (d <= (int)TOTAL_ELEMENTS - 2)
x = array[d+1];
printf("%d/n", x);
return 0;
}
运行结果分别为0 和23,这是因为sizeof返回的unsinged int,在d <= TOTAL_ELEMENTS - 2语句中发生了强制转换,d成为一个极大的正整数,因此程序一中if语句当然不会执行。从这个例子可以得到的启示是在代码中尽量不要使用无符号数,以避免因为强制类型转换而把负数转换为非常大的正数。

被折叠的 条评论
为什么被折叠?



