我正在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, $sp, 8 # delete current top , top-1 from the stack
jr $ra
end:
sb $a2,res
jr $ra