MIPS递归功能无法正常工作

问题描述

我正在MIPS中执行阶乘递归函数。这是代码

fact: #a1 = n   a2 = res

addi $t1,$zero,1
beq $a1,$t1,end  # if n == 1 return res
#else
mul $a2,$a2,$a1
subi $a1,$a1,1

jal fact


end:
sb $a2,res
jr $ra

问题是,仅当我编写j fact而不是jal fact时,此代码才有效,而jal fact出于某种原因,代码将无限运行。

解决方法

    fact: #a1 = n   a2 = res

addi $t1,$zero,1
beq $a1,$t1,end  # if n == 1 return res
#else
addi $sp,$sp,8
sw $a1,0($sp) #  in the top of the stack store the argument you called fact
sw $ra,4($sp) # ra holds the return adress ( I do not know whether you know it)
mul $a2,$a2,$a1
subi $a1,$a1,1
jr $ra

jal fact
lw $a1,0($sp) # load the value from memory adress that the top stack pointer shows to back to the register a1
lw $ra,4($sp) 
addi $sp,8 # delete current top,top-1 from the stack
jr $ra

end:
sb $a2,res
jr $ra