定义变量如下:
u8 datacode = 0x00;
u8 Rdatacode = 0xFF;
在KEIL uVision3中用到如下代码if(~Rdatacode != datacode),单步调试该表达式结果竟然为真?但若用表达式Rdatacode = ~Rdatacode,则运行后Rdatacode得到正常结果0x00。
实在不解,特此请教!
应该是这样吧
Rdatacode &=~Rdatacode;
Rdatacode = ~Rdatacode就是把Rdatacode按位取反后在赋值给Rdatacode,这个没错,运行结果也是对的
如果int是32位,
~0xFF结果不是0X00,而是是0XFFFFFF00,
0XFFFFFF00!=0x00,
当然为真。
5# mcu5i51
为何我的偏偏不行?版本为uVision3 V3.80,芯片是STM32F103VCH
已经说的很明白了。
5楼用的肯定是KEIL C51。
为什么KEIL C51能行?而 KEIL MDK却不行呢?
原因是KEIL C51很不符合C标准的C编译器。
而KEIL MDK则是相当遵守C标准的C编译器。
确如上官所言,默认int为32位,加入类型转换后逻辑才正确。
C语言标准规定:
The result of the ~ operator is the bitwise complement of its (promoted) operand (that is,
each bit in the result is set if and only if the corresponding bit in the converted operand is
not set).The integer promotions are performed on the operand, and the result has the
promoted type.If the promoted type is an unsigned type, the expression ~E is equivalent
to the maximum value representable in that type minus E.