看了一篇博文,该文章中有如下描述
1 #include <stdio.h> 2 3 int main() 4 { 5 unsigned short a = 1; 6 unsigned short b = 0 7 8 if (a < (b-1)) //a和b-1的结果-1都被转换为int类型进行比较,1<-1,显然false 9 { 10 printf("in if\n"); 11 } 12 13 return 14 15 }
预期结果时打印“in if”,但实际运行时却发现啥都没有输出。改为如下代码就可以正常输出“in if”,此时与预期相符
; int b = 0; b-1的结果-1,被转换为0xffffffff,1<0xffffffff,显然true啊 15 }
使用汇编,直接对比两者结果(公司安全不让发送外网图片..),发现主要差异在如下5行,前四行中对short进行了扩展,由2字节扩展为4字节,高位填充0。导致运行结果与与预期不符合的原因就在第5行:jge 8048461
1 08048425 <main>: 2 8048425: 8d 4c 24 04 lea 0x4(%esp),%ecx 3 8048429: 83 e4 f0 and $0xfffffff0,1)">esp 4 804842c: ff 71 fc pushl -0x4(%ecx) 5 804842f: 55 push %ebp 6 8048430: 89 e5 mov %esp,1)"> 7 8048432: 51 push % 8 8048433: 83 ec 14 sub $0x14,1)">esp 9 8048436: 66 c7 45 f6 01 00 movw $0x1,-0xa(%ebp) 10 804843c: 45 f4 00 0x0,1)">0xc(%11 8048442: 0f b7 45 f6 movzwl -0xa(%ebp),1)">eax 12 8048446: 0f b7 55 f4 movzwl -0xc(%ebp),1)">edx 13 804844a: 83 ea 01 sub $edx 14 804844d: 39 d0 cmp %edx,1)">eax 15 804844f: 7d 10 jge 8048461 <main+0x3c> 16 8048451: 83 ec 0c sub $0xc,1)">17 8048454: 68 85 04 08 push $0x8048500 18 8048459: e8 a2 fe ff ff call 8048300 <puts@plt> 19 804845e: 83 c4 10 add $0x10,1)">20 8048461: b8 00 mov $21 8048466: 8b 4d fc mov -0x4(%ebp),1)">22 8048469: c9 leave 23 804846a: 8d 61 fc lea -0x4(%ecx),1)">24 804846d: c3 ret 25 804846e: 66 90 xchg %ax,%ax
汇编中的数值是没有符号之分的,但指令是有符号分别的,上述使用的jge即是有符号比较的方式,导致比较结果为:if (1<-1),为false,不会打印字符串
指令 | 含义 | 运算符号 |
jbe | unsigned below or equal (lower or same) | <= |
jae | unsigned above or equal (higher or same) | >= |
jb | unsigned below (lower) | < |
ja | unsigned above (higher) | > |
jle | signed less or equal | <= |
jge | signed greater or equal | >= |
jl | signed less than | < |
jg | signed greater than | > |
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。