概述
while语句是3种循环语句的一种。如果条件满足则不断执行。
看代码。
#include <stdio.h>
int main(void)
{
int x=0;
while(x*x<1000)
{
printf("%dn",x*x);
x++;
}
return 0;
}
看汇编代码。
.section .rodata
.LC0:.string "%dn"
.text
.global main
main:
pushl %ebp
movl %esp,%ebp
subl $4,%esp
movl $0,-4(%ebp)
jmp .L1
.L2:
movl -4(%ebp),%eax
imull -4(%ebp),%eax
pushl %eax
pushl $.LC0
call printf
addl $8,%esp
addl $1,-4(%ebp)
..L1:
movl -4(%ebp),%eax
imull -4(%ebp),%eax
cmpl $1000,%eax
jl .L2
movl $0,%eax
leave
ret
下面分析以上代码
jmp .L1 跳转到.L1。movl -4(%ebp),%eax imull -4(%ebp),%eax cmpl $1000,%eax jl .L2 比较xx是否小于1000,如果是的话,则跳转.L2继续执行。相当于执行while(xx<1000),如果条件满足则执行。
.L1处用于判断。.L2处用于执行。
for循环一般用于循环计数。
#include <stdio.h>
int main(void)
{
int i;
for(i=0;i=100;i++)
{
if((i&1)==0)
{
printf("%dn",i);
}
}
return 0;
}
for 代码可以看成while代码。
#include <stdio.h>
int main(void)
{
int i;
i=0;
while(i<100)
{
if((i&1)==0)
printf("%dn",i);
i++;
}
return 0;
}
汇编代码
.section .rodata
.LC0:.string "%dn"
.text
.global main
main:
pushl %ebp
movl %esp,%ebp
subl $4,%esp
movl $0,-4(%ebp)
jmp .L1
.L2:
movl -4(%ebp),%eax
andl $1,%eax
cmpl $0,%eax
jne .L3
pushl -4(%ebp)
pushl $.LC0
call printf
addl $8,%esp
.L3:
addl $1,-4(%ebp)
..L1:
cmpl $100,-4(%ebp)
jl .L2
movl $0,%eax
leave
ret
基本与while循环相同。
do-while循环
#include <stdio.h>
int main(void)
{
int i=0;
do
{
printf("%dn",i);
i++;
}while(i<100);
return 0;
}
汇编代码
.section .rodata
.LC0:.string "%dn"
.text
.global main
main:
pushl %ebp
movl %esp,%ebp
subl $4,%esp
movl $0,-4(%ebp)
.L1:
pushl -4(%ebp)
pushl $.LC0
call printf
addl $8,%esp
addl $1,-4(%ebp)
cmpl $100,-4(%ebp)
jl .L1
movl $0,%eax
leave
ret
do-while循环先执行后判断。
最后
以上就是正直期待为你收集整理的从C语言到汇编(三)循环语句的全部内容,希望文章能够帮你解决从C语言到汇编(三)循环语句所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复