您的位置:首页 > 其它

030 函数的递归调用

2015-02-13 15:38 507 查看
/********************030 函数的递归调用************************
* 将一个整数你转换成为字符串。
* C语言精彩编程百例 第30*/
#include<stdio.h>

void convert(int n)
{
int i;
i=n/10;
if(i!=0)
convert(i);
putchar(n%10+'0');
}

void main()
{
int number;
printf("输入整数:");
scanf("%d",&number);
printf("输出是:");
if(number<0)
{
putchar('-');
number=-number;
}
convert(number);
putchar('\n');
}


编译器汇编的结果:

.file   "030.c"
.text
.align 2
.globl _convert
.def    _convert;   .scl    2;  .type   32; .endef
_convert:
pushl   %ebp
movl    %esp, %ebp
subl    $8, %esp
movl    8(%ebp), %ecx       # ecx=n
movl    $1717986919, %eax  # eax=1717986919
imull   %ecx            # edx:eax=n*1717986919
sarl    $2, %edx       # edx=n*1717986919/2^34=n*0.1
movl    %ecx, %eax      # eax=n
sarl    $31, %eax      # 右移31位,取n的符号
subl    %eax, %edx      # edx = n*0.1 - n的符号, 向零取整结果
movl    %edx, %eax      # eax = n*0.1
movl    %eax, -4(%ebp)      # i=n/10
cmpl    $0, -4(%ebp)       # if(i!=0)
je  L4
subl    $12, %esp      # 调用 _convert
pushl   -4(%ebp)
call    _convert
addl    $16, %esp
L4:
subl    $12, %esp      # 准备 printf
movl    8(%ebp), %ecx       # ecx=n
movl    $1717986919, %eax  # eax=1717986919
imull   %ecx            # edx:eax=n*1717986919
sarl    $2, %edx       # edx=n*1717986919/2^34=n*0.1
movl    %ecx, %eax      # eax=n
sarl    $31, %eax      # 右移31位,取n的符号
subl    %eax, %edx      # edx = n*0.1 - n的符号, 向零取整结果
movl    %edx, %eax      # edx = n/10
sall    $2, %eax       # eax=n*0.1*4
addl    %edx, %eax              # eax=n*0.1*5
addl    %eax, %eax      # eax=n*0.1*10
subl    %eax, %ecx      # ecx=n-n*0.1*10
movl    %ecx, %eax      # eax=n%10 // 编译器为mod做的优化 ...
addl    $48, %eax      # n%10+'0'
pushl   %eax
call    _putchar
addl    $16, %esp
leave
ret
.def    ___main;    .scl    2;  .type   32; .endef
LC0:
.ascii "\312\344\310\353\325\373\312\375\243\272\0"
LC1:
.ascii "%d\0"
LC2:
.ascii "\312\344\263\366\312\307\243\272\0"
.align 2
.globl _main
.def    _main;  .scl    2;  .type   32; .endef
_main:
pushl   %ebp
movl    %esp, %ebp
subl    $8, %esp
andl    $-16, %esp
movl    $0, %eax
movl    %eax, -8(%ebp)
movl    -8(%ebp), %eax
call    __alloca
call    ___main
subl    $12, %esp
pushl   $LC0
call    _printf
addl    $16, %esp
subl    $8, %esp
leal    -4(%ebp), %eax
pushl   %eax
pushl   $LC1
call    _scanf
addl    $16, %esp
subl    $12, %esp
pushl   $LC2
call    _printf
addl    $16, %esp
cmpl    $0, -4(%ebp)
jns L6
subl    $12, %esp
pushl   $45
call    _putchar
addl    $16, %esp
leal    -4(%ebp), %eax
negl    (%eax)
L6:
subl    $12, %esp
pushl   -4(%ebp)
call    _convert
addl    $16, %esp
subl    $12, %esp
pushl   $10
call    _putchar
addl    $16, %esp
leave
ret
.def    _scanf; .scl    2;  .type   32; .endef
.def    _printf;    .scl    2;  .type   32; .endef
.def    _putchar;   .scl    2;  .type   32; .endef
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: