msg4: .asciiz "\nAverage is: "
main
jal AverageFunction
la $a0, msg4
li $v0, 4
syscall
move $a0, $t
li $v0, 1
syscall
sumfunction:
la $t3, array
sum:
bge $t4, $t1, done
lw $t0, 0($t3)
add $t5, $t5, $t0
addi $t3, $t3, 4
addi $t4, $t4, 1
b sum
done:
jr $ra
AverageFunction:
jal sumfunction
div $t6, $t5, $t1
jr $ra
运行此程序时没有打印。我需要从另一个函数调用函数并返回main -------------
答案 0 :(得分:1)
当AverageFunction
调用sumfunction
时,它会使用新的返回地址(即$ra
之后的指令的地址)覆盖jal sumfunction
。因此,当AverageFunction
尝试返回时,它会以无限循环结束。
您需要以某种方式保存旧的返回地址,然后将其恢复。一种方法是使用堆栈:
AverageFunction:
addi $sp,$sp,-4 # "push" operations pre-decrement the stack pointer
sw $ra,($sp) # Save the current return address on the stack
jal sumfunction
div $t6, $t5, $t1
lw $ra, ($sp) # Restore the old return address
addi $sp,$sp,4 # "pop" operations post-increment the stack pointer
jr $ra