Subroutines part 1

subroutine is a collective term that refers to procedures and functions. The difference between the two is that functions return a value, and procedures do not. Not all languages distinguish between the two. Pascal is one that does. In Java and C, a procedure is a function whose return value is void.

The picture below shows a subroutine in MIPS assembly language. The name of the jal instruction comes from "jump and link". The jal, like j, is a j-format instruction and works the same way with one exception: the link part is there to make provision for a return at the end of the subroutine. Register $31 is dedicated to the purpose of holding the return address of a subroutine. That is why its name is $ra. When the jal instruction is executed, two things happen:

In the example below, the next instruction executed after the jal is the one at label subr. Then the other instructions in the right column are executed. The jr instruction at the bottom of the right column copies the value in $ra into the program counter. This returns to the instruction immediately after the jal.