我的程序是用C ++编写的,其中嵌入了一些x86汇编语言。我有两个嵌套的for循环用汇编语言,我必须经历。但是,当我编译程序时,我得到一个无限循环。 C ++中的等效程序看起来像这样:
#include<iostream>
using namespace std;
int main()
{
int a[4] = {3,6,4,7};
for(int k = 0 ; k < 4;k++)
{
for(int l = 0 ; l < a[k];l++)
{
cout<<'*';
}
cout<<endl;
}
system("pause");
return 0;
}
/*
***
******
****
*******
Press any key to continue . . .
*/
这是相同的事情,但是在装配混合的情况下完成。
#include<iostream>
using namespace std;
void output(); //function for making an '*'
void makeSpace(); //function for making a space
int main()
{
int a[4]={3,6,4,7};
int counter = 0; //counter that will be used for first forloop
int counter2 = 0; // counter to be used for second forloop
_asm{
mov ebx,0 // this is to move from element 0,1,2,3,4, through the array
mov ecx,0 // ecx will get the data from the array, only to be used as a
// counter in forloop2 though.
for1:
cmp counter,4 //begins for firloop
je starts
mov ecx,[a+ebx] // move the 0th element from array to ecx
add ebx,4// ebx = ebx+4, I'm doing this to advance the array position (int)
inc counter// increment counter by one
for2:
cmp counter2,ecx //begin forloop2,
je starts2
call output
inc counter2 //increment counter2 by one
jmp for2
starts2:
call makeSpace
jmp for1
starts:
}
return 0;
}
void output()
{
cout<<'*';
}
void makeSpace()
{
cout<<endl;
}
为什么会导致无限循环?
答案 0 :(得分:2)
至少需要修改两件事:
当您致电output()
时,只保证以下寄存器不会被删除:
edi
,esi
,ebx
和ebp
特别是,您正在使用ecx
,该功能可以废弃。
您永远不会将counter2
重置为0,因此内部循环不等同于您的C代码。
答案 1 :(得分:0)
我相信这里的答案是,在调用函数Output
和MakeSpace
之前,您永远不会保留寄存器。标准函数标头不保证ecx
代码中使用的ebx
或asm
寄存器的任何内容。