从C语言到汇编(三)循环语句

while语句是3种循环语句的一种。如果条件满足则不断执行。
看代码。

#include <stdio.h>
int main(void)
{
	int x=0;
	while(x*x<1000)
	{
		printf("%d\n",x*x);
		x++;
	}
	return 0;
}

看汇编代码。

.section .rodata
	.LC0:.string "%d\n"
.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("%d\n",i);
		}
	}
	return 0;
}

for 代码可以看成while代码。

#include <stdio.h>
int main(void)
{
	int i;
	i=0;
	while(i<100)
	{
		if((i&1)==0)
			printf("%d\n",i);
		i++;
	}
	
	return 0;
}

汇编代码

.section .rodata
	.LC0:.string "%d\n"
.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("%d\n",i);
		i++;
	}while(i<100);
	
	return 0;
}

汇编代码

.section .rodata
	.LC0:.string "%d\n"
.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循环先执行后判断。

发布了185 篇原创文章 · 获赞 18 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/pk_20140716/article/details/103160571