环境:VC++
do while 会先执行do里面的循环体,执行完去执行while的条件判断,如果为真,继续执行do里面的循环体,如果为假,则结束循环
C程序:
#include "stdio.h"
int main()
{int i=1,sum=0;do{sum+=i;i++;}while(i<=100);printf("sum=%d\n",sum);return 0;
}
上面先执行sum+=i;i++;
,接着执行i<=100
,如果为true,则继续执行do循环,否则,结束循环。
反汇编:
5: int i=1,sum=0;
00401028 C7 45 FC 01 00 00 00 mov dword ptr [ebp-4],1
0040102F C7 45 F8 00 00 00 00 mov dword ptr [ebp-8],0
6: do{
7: sum+=i;
00401036 8B 45 F8 mov eax,dword ptr [ebp-8]
00401039 03 45 FC add eax,dword ptr [ebp-4]
0040103C 89 45 F8 mov dword ptr [ebp-8],eax
8: i++;
0040103F 8B 4D FC mov ecx,dword ptr [ebp-4]
00401042 83 C1 01 add ecx,1
00401045 89 4D FC mov dword ptr [ebp-4],ecx
9: }while(i<=100);
00401048 83 7D FC 64 cmp dword ptr [ebp-4],64h
0040104C 7E E8 jle main+26h (00401036)
10: printf("sum=%d\n",sum);
0040104E 8B 55 F8 mov edx,dword ptr [ebp-8]
00401051 52 push edx
00401052 68 1C 20 42 00 push offset string "sum=%d\n" (0042201c)
00401057 E8 34 00 00 00 call printf (00401090)
0040105C 83 C4 08 add esp,8
11: return 0;
0040105F 33 C0 xor eax,eax
12: }
- jle:小于等于,则跳转
从上面的程序我们可以看出,sum+=i就是
00401036 8B 45 F8 mov eax,dword ptr [ebp-8]
00401039 03 45 FC add eax,dword ptr [ebp-4]
0040103C 89 45 F8 mov dword ptr [ebp-8],eax
i++就是:
0040103F 8B 4D FC mov ecx,dword ptr [ebp-4]
00401042 83 C1 01 add ecx,1
00401045 89 4D FC mov dword ptr [ebp-4],ecx
汇编执行完这几条语句,就去执行
00401048 83 7D FC 64 cmp dword ptr [ebp-4],64h
0040104C 7E E8 jle main+26h (00401036)
比较[ebp-4]和100的大小,如果小于等于就跳转到00401036执行,否则往下执行,相当于C中i<=100,如果小于等于,继续执行循环体,否则结束
C和混编混合编程:
#include "stdio.h"int main()
{/*int i=1,sum=0;do{sum+=i;i++;}while(i<=100);printf("sum=%d\n",sum);*/char *str="sum=%d\n";__asm{//相当于 int i=1,sum=0mov eax,1mov ebx,0//相当于 sum+=i
ee: add ebx,eax//相当于 i++inc eax//相当于while(i<=100)cmp eax,100jle ee//相当于printfpush ebxpush strcall printfadd esp,8}return 0;
}