[C Tips]善待无符号数
猜猜下面代码的输出是什么?
#include <stdio.h>
int array[] = {1,2,3,4,5,6,7,8,9,10};
#define TOTAL_ELEMENTS sizeof(array)/sizeof(array[0])
int main(){
int d = -1;
printf("d:%d\n",d);
if(d > TOTAL_ELEMENTS){
printf("d:%d d > TOTAL_ELEMENTS:%d\n",d,TOTAL_ELEMENTS);
}
if(d < (unsigned char)1){
printf("d:%d d < unsigned char 1\n",d);
}
if(d > (unsigned int)1){
printf("d:%d d > unsigned int 1",d);
}
getchar();
}
int array[] = {1,2,3,4,5,6,7,8,9,10};
#define TOTAL_ELEMENTS sizeof(array)/sizeof(array[0])
int main(){
int d = -1;
printf("d:%d\n",d);
if(d > TOTAL_ELEMENTS){
printf("d:%d d > TOTAL_ELEMENTS:%d\n",d,TOTAL_ELEMENTS);
}
if(d < (unsigned char)1){
printf("d:%d d < unsigned char 1\n",d);
}
if(d > (unsigned int)1){
printf("d:%d d > unsigned int 1",d);
}
getchar();
}
ANSI C编译器下的结果为:
d:-1
d:-1 d > TOTAL_ELEMENTS:10
d:-1 d < unsigned char 1
d:-1 d > unsigned int 1
知道静悄悄的改变发生在哪儿了么? ;-)