编译环境:C-FREE5.0
编译器: 标准C89(32位)
代码1:
#include
#include
int main(void)
{
/*
unsigned short i;
unsigned short j;
unsigned short k;*/
short i;
short j;
short k;
i = 0;
j = 0xffff;
k = ~j;
printf("i = %d ,", i);
printf("%x\n", i);
printf("j = %d ,", j);
printf("%x\n", j);
printf("k = %d ,", k);
printf("%x\n", k);
printf("~i = %d ,", ~i);
printf("%x\n", ~i);
printf("~j = %d ,", ~j);
printf("%x\n", ~j);
if(i == ~j){
printf("i == ~j\n");
}
else{
printf("i != ~j\n");
}
if(i == k){
printf("i == k\n");
}
else{
printf("i != k\n");
}
return 1;
}
运行结果:
#include
#include
int main(void)
{
unsigned short i;
unsigned short j;
unsigned short k;
/*
short i;
short j;
short k;*/
i = 0;
j = 0xffff;
k = ~j;
printf("i = %d ,", i);
printf("%x\n", i);
printf("j = %d ,", j);
printf("%x\n", j);
printf("k = %d ,", k);
printf("%x\n", k);
printf("~i = %d ,", ~i);
printf("%x\n", ~i);
printf("~j = %d ,", ~j);
printf("%x\n", ~j);
if(i == ~j){
printf("i == ~j\n");
}
else{
printf("i != ~j\n");
}
if(i == k){
printf("i == k\n");
}
else{
printf("i != k\n");
}
return 1;
}
运行结果如下:
只要懂得数据在内存中存储的形式和按位取反的意义,相信理解上面两段代码就不成问题了。这确实是C里面最基本的概念了,但最近写代码时却没想起来,直接使用形式“if(i == ~j)”,很显然,这样是很危险的,尤其是当定义i和j为无符号数据类型时,很可能不会得出想要的结果。 然而,神奇的是,定义的无符号字符型数据经过keil C51编译器编译之后在8位51单片机上跑,正常;而用IAR编译器编译过之后,就会出现异常,推测应该是keilC51编译器进行了一些特殊处理吧。。。 为了保证万无一失,最好是进行取反运算之后,对其结果进行强制类型转换,比如赋给一个变量,然后再进行比较或者其他运算。
阅读(4228) | 评论(0) | 转发(0) |