Mips函数调用

时间:2014-03-27 20:05:04

标签: function loops mips

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 -------------

1 个答案:

答案 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