http://www.ouravr.com/bbs/bbs_content.jsp?bbs_sn=838295&bbs_page_no=1&bbs_id=1000
编译器使用:WinAVR-20070525
uint l=0;
uchar i=0;
uchar j=0;
uchar tmp[6];
tmp[4]=0xA0;
tmp[5]=0;
j=0x40;
问题是,下面第一种编译出来if条件竟然不成立,我明明把变量已经定义为无符号类型。
将j-tmp[4]的结果强制转换后,才能成立。
第一种情况下编译结果
if(((j-tmp[4])==tmp[4])&&(tmp[5]==0)) //
+00000507: 811D LDD R17,Y+5 Load indirect with displacement
+00000508: 2F21 MOV R18,R17 Copy register
+00000509: 2733 CLR R19 Clear Register
+0000050A: 2F80 MOV R24,R16 Copy register
+0000050B: 2799 CLR R25 Clear Register
+0000050C: 1B82 SUB R24,R18 Subtract without carry
+0000050D: 0B93 SBC R25,R19 Subtract with carry
+0000050E: 1728 CP R18,R24 Compare
+0000050F: 0739 CPC R19,R25 Compare with carry
+00000510: F419 BRNE PC+0x04 Branch if not equal
+00000511: 818E LDD R24,Y+6 Load indirect with displacement
+00000512: 2388 TST R24 Test for Zero or Minus
+00000513: F081 BREQ PC+0x11 Branch if equal
第二种编译结果
if(((uchar)(j-tmp[4])==tmp[4])&&(tmp[5]==0)) //
+00000507: 811D LDD R17,Y+5 Load indirect with displacement
+00000508: 2EF0 MOV R15,R16 Copy register
+00000509: 1AF1 SUB R15,R17 Subtract without carry
+0000050A: 151F CP R17,R15 Compare
+0000050B: F419 BRNE PC+0x04 Branch if not equal
+0000050C: 818E LDD R24,Y+6 Load indirect with displacement
+0000050D: 2388 TST R24 Test for Zero or Minus
+0000050E: F079 BREQ PC+0x10 Branch if equal
在第一种运算中j-tmp[4]被扩展为整型运算,通过反汇编看到tmp[4]-->R19,R18; j-->R25,R24中。
所以当j>tmp[4]的时候,可以得到预期的结果,当j<tmp[4]的时候就出问题了。如果将j-tmp[4]得值赋给第三个变量,例如k=j-tmp[4],再判断k?=tmp[4]得时候,也可以得到预期得结果。
感谢yyccaa 给出了解释。http://www.ouravr.com/bbs/bbs_content.jsp?bbs_sn=795415
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=53586
在ISO C99规范中相关得解释:P79,
1 The operand of the unary + or - operator shall have arithmetic type; of the ˜ operator,
integer type; of the ! operator, scalar type.
Semantics
2 The result of the unary + operator is the value of its (promoted) operand. The integer
promotions are performed on the operand, and the result has the promoted type.
3 The result of the unary - operator is the negative of its (promoted) operand. The integer
promotions are performed on the operand, and the result has the promoted type.
文章评论(0条评论)
登录后参与讨论