Simple Subroutine Linkage


There are two subroutine instructions, jal and jr.
jal label         # jump and link
This instruction is similar to a jump, in that control is passed to the label specified in the instruction. Additionally, however, the address of the instruction following the jump instruction is automatically placed into register $31 (or $ra).

jr rs         # jump register
This instruction transfers control to the address contained in rs. Thus, if a jr $31 instruction is executed at the end of a subroutine which was invoked by a jal, control will return to the instruction following the jal.
Arithmetic Series Calculation (1+2+3+...+n)
Without Using a Subroutine Using a Subroutine
       .data
 n:    .word   0
 ans:  .word   0

       .text
 main: li    $v0, 5
       syscall
       sw    $v0, n
       j     calc
 ret:  lw    $a0, ans
       li    $v0, 1
       syscall

 end:  li    $v0, 10
       syscall


 ###### calc routine ######

 calc: lw    $t0, n
       li    $t1, 0
       sw    $t1, ans
 next: 
       add   $t1, $t1, $t0
       sw    $t1, ans
       sub   $t0, $t0, 1
       j     next
 
       .data
 n:    .word   0
 ans:  .word   0

       .text
 main: li    $v0, 5
       syscall
       sw    $v0, n
       jal   calc
       lw    $a0, ans
       li    $v0, 1
       syscall

 end:  li    $v0, 10
       syscall


 ###### calc subroutine ######

 calc: lw    $t0, n
       li    $t1, 0
       sw    $t1, ans
 next: 
       jr    $31

 cont: add   $t1, $t1, $t0
       sw    $t1, ans
       sub   $t0, $t0, 1
       j     next
 




      News of the new president was    
      music to my ears (good to hear) — she’s terrific.