0

私のコードをメインから呼び出されるサブルーチンにする方法について誰かアドバイスをもらえますか?

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

1 に答える 1

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 レジスタは戻り値に使用されます。

于 2013-11-05T20:52:26.463 に答える