如何在MASM中保存递归函数的最后一个值



本质上,我编写了一个函数,可以递归地查找两个数字的GCD。我正试图将递归调用的最后一个值存储到firstVal中,以便将其打印到屏幕上。我编写它的方式打印递归的所有值。

GCD proc firstVal: dword, secondVal: dword
mov edx, 0         ;clear edx for div
cmp secondVal, 0   ;if b is 0 (only way to exit recursion)
jz foundGCD        ;then a is the gcd
mov eax, firstVal  ;to find a mod b
div secondVal      ;div a by b and check ah
mov ecx, secondVal       ;old b in ecx
mov firstVal, ecx        ;now store ecx in a
mov secondVal, edx       ;store a mod b in b
invoke GCD, firstVal, secondVal  ;recursion
foundGCD:
call crlf          ;newline
mov eax, firstVal  ;firstVal holds the gcd
call writedec      ;I think the problem sits somewhere here?
call waitmsg
ret
GCD endp

如何保存递归过程的最后一个值?

问题是在递归调用返回后,在invoke GCD调用后面的语句处继续执行:foundGCD标签,它将生成输出。

invoke之后应该做的是处理递归的结果,在本例中,递归是一个简单的ret

invoke GCD, firstVal, secondVal  ;recursion
ret

这样,我们可以看到递归是尾递归,因此递归调用可以用无条件跳转代替(留给读者练习(。

最新更新