在C语言里面,以下代码是否会打印文本?
unsigned ua = 1;
unsigned ub = 2;
if (ua - ub < 0){
printf("%d is equal to \"true\"",(ua - ub));
}
答案是不会的,因为ua
和ub
都是unsigned
类型数值,系统默认认为算式ua - ub
的结果也是unsigned
类型的
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len) {
size_t i;
for(i=0;i<len;i++){
printf("%.2x",start[i]);
}
printf("\n");
}
unsigned ua = 1;
unsigned ub = 2;
unsigned uc = ua - ub;
printf("%u\n",unsigned(uc));
show_bytes((byte_pointer)&ua,sizeof(unsigned));
show_bytes((byte_pointer)&ub,sizeof(unsigned));
show_bytes((byte_pointer)&uc,sizeof(unsigned));
4294967295
01000000
02000000
ffffffff
打印出他们的字节码观察,分析,得知ua - ub
运算溢出,得到ffffffff
,表示成十进制为4294967295
,显然大于0,所以以上结果可以解释清楚。