簡體   English   中英

x86-assembly中的遞歸函數

[英]Recursive function in x86-assembly

我在x86匯編代碼中有一個方法method(int a, int b)

method:
  pushl  %ebx
  subl   $24 , %esp
  movl   32(%esp ) , %ebx
  movl   36(%esp ) , %edx
  movl   $1 , %eax
  testl  %edx , %edx
  je     .L2
  subl   $1 , %edx
  movl   %edx , 4(%esp )
  movl   %ebx , (%esp )
  call   method
  imull  %ebx , %eax
.L2:
  addl   $24 , %esp
  popl   %ebx
  ret

但是我只是無法繞開它的功能。

a寫在%ebxb寫在%edx

%eax用1初始化。

如果%edx不是0,I 1。減去從%edx和推%edx%ebx在堆疊和呼叫method一次。 我只是不明白它的作用。 而且到達imull %ebx, %eax這行不是不可能嗎?

如果有人可以向我解釋此方法的基本功能,我將非常高興。

imull %ebx, %eax遞歸調用返回時到達imull %ebx, %eax

該函數似乎正在通過遞歸計算輸入變量(a b )的冪,並且該值通過%eax返回。

這種工作方式是,當b為0並返回1時,基本情況為。 b > 0時,返回method(a, b-1) * a

它基本上等效於以下C函數:

int method(int a, int b)
{
  if (b == 0)
    return 1;

  return method(a, b-1) * a;  
}

或更接近匯編代碼:

int method(int a, int b)
{
  if (b == 0)
    return 1;

  int temp = method(a, b-1);

  return temp * a;  // we do get here when the recursion is over,
                    // the same ways as we get to imull %ebx, %eax
                    // in your assembly code when the recursion is over
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM