C语言的类型转换很重要,经常出现,但是往往不被人注意,而在汇编代码当中就暴露无遗了。
如下列代码:
char ch;
while ((ch = getchar()) != '#')
putchar(ch);
反汇编后:
.text:00401006 mov eax, stru_407030._cnt
.text:0040100B sub eax, 1
.text:0040100E mov stru_407030._cnt, eax
.text:00401013 cmp stru_407030._cnt, 0
.text:0040101A jl short loc_40103D
.text:0040101C mov ecx, stru_407030._ptr
.text:00401022 movsx edx, byte ptr [ecx]
.text:00401025 and edx, 0FFh
.text:0040102B mov [ebp+var_8], edx
.text:0040102E mov eax, stru_407030._ptr
.text:00401033 add eax, 1
.text:00401036 mov stru_407030._ptr, eax
.text:0040103B jmp short loc_40104D
.text:0040103D ; ---------------------------------------------------------------------------
.text:0040103D
.text:0040103D loc_40103D: ; CODE XREF: _main+1Aj
.text:0040103D push offset stru_407030 ; File
.text:00401042 call __filbuf
.text:00401047 add esp, 4
.text:0040104A mov [ebp+var_8], eax ; 这里是重点 注意getchar()的返回类型是int,要赋给char需要类型转换
;以上都是getchar()的汇编代码,在很多实现中,getchar()只是一个macro,所以才会展开这么多代码
.text:0040104D
.text:0040104D loc_40104D: ; CODE XREF: _main+3Bj
.text:0040104D mov cl, byte ptr [ebp+var_8]
.text:00401050 mov [ebp+var_4], cl
.text:00401053 movsx edx, [ebp+var_4] ;同样,0x23h是int类型,和它比较也要做转换,所以要用带符号扩展的movsx
.text:00401057 cmp edx, 23h
.text:0040105A jz short loc_4010B4 ;以下是putchar()的代码
.text:0040105C mov eax, File._cnt
.text:00401061 sub eax, 1
.text:00401064 mov File._cnt, eax
.text:00401069 cmp File._cnt, 0
.text:00401070 jl short loc_40109A
.text:00401072 mov ecx, File._ptr
.text:00401078 mov dl, [ebp+var_4]
.text:0040107B mov [ecx], dl
.text:0040107D movsx eax, [ebp+var_4]
.text:00401081 and eax, 0FFh
.text:00401086 mov [ebp+var_C], eax
.text:00401089 mov ecx, File._ptr
.text:0040108F add ecx, 1
.text:00401092 mov File._ptr, ecx
.text:00401098 jmp short loc_4010AF
.text:0040109A ; ---------------------------------------------------------------------------
.text:0040109A
.text:0040109A loc_40109A: ; CODE XREF: _main+70j
.text:0040109A push offset File ; File
.text:0040109F movsx edx, [ebp+var_4]
.text:004010A3 push edx ; Ch
.text:004010A4 call __flsbuf
.text:004010A9 add esp, 8
.text:004010AC mov [ebp+var_C], eax
.text:004010AF
.text:004010AF loc_4010AF: ; CODE XREF: _main+98j
.text:004010AF jmp loc_401006