C语言的类型转换

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

相关推荐
晓蛋1 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
傲世仙尊1 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿1 天前
重载、重写(覆盖)、重定义区别
c语言
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
phltxy1 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
phltxy1 天前
C 语言中的数据存储:从类型到二进制位
c语言
龙亘川1 天前
一网统管AI平台民生业务实践:基于城市数字底座赋能公积金业务服务升级
大数据·安全·智慧城市·开源软件·数据可视化·政务