有人可以就如何将我的代码变成从main调用的子程序给出一些建议吗?
.data
inputOne: .word 2 # Value 1
inputTwo: .word 3 # Value 2
counter: .word 0 # Adds the amount of times that we go through the loop
sum: .word 0 # Where the result of the addition goes
.text
main:
lw $t2, inputOne # Load 2 into register t2
lw $t3, inputTwo # Load 3 into register t3
lw $t4, counter # Load 0 into register t4
lw $t5, sum # Load 0 into register t5
topOfLoop: # Start of the loop
beq $t4, $t2, bottomOfLoop # Until t4 is equal to t2, the loop will continue
addi $t5, $t5, 3 # Adds 3 to register t5 ( Sum)
addi $t4, $t4, 1 # Adds 1 to register t5 (Counter)
j topOfLoop # Jumps to the top of the loop
bottomOfLoop: # End of the loop
sw $t5, sum #Storing the value in $t5 into sum
答案 0 :(得分:1)
使用jal和jr $ ra:
.data
inputOne: .word 2 # Value 1
inputTwo: .word 3 # Value 2
counter: .word 0 # Adds the amount of times that we go through the loop
sum: .word 0 # Where the result of the addition goes
.text
main:
lw $t2, inputOne # Load 2 into register t2
lw $t3, inputTwo # Load 3 into register t3
lw $t4, counter # Load 0 into register t4
lw $t5, sum # Load 0 into register t5
jal sub # go to sub and store the address of the next position in $ra
li $vo, 10
syscall #end program
sub:
topOfLoop: # Start of the loop
beq $t4, $t2, bottomOfLoop # Until t4 is equal to t2, the loop will continue
addi $t5, $t5, 3 # Adds 3 to register t5 ( Sum)
addi $t4, $t4, 1 # Adds 1 to register t5 (Counter)
j topOfLoop # Jumps to the top of the loop
bottomOfLoop: # End of the loop
sw $t5, sum #Storing the value in $t5 into sum
jr $ra # jump to the address in $ra, as it is filled by jal
记住:按照惯例,$ t寄存器可以由子程序改变,$ s寄存器必须在子程序结束之前由子程序恢复,$ a寄存器用于参数,$ v寄存器用于返回值。