Function Basics
Functions (also called procedures or subroutines) are reusable blocks of code that perform specific tasks. In MIPS, functions use the jal (jump and link) instruction to call and jr $ra to return. The calling convention defines how arguments are passed and values returned.
Key Points:
- jal saves return address in $ra and jumps
- jr $ra returns to caller
- $a0-$a3 pass first 4 arguments
- $v0-$v1 return values
Example Code
# Function definition
my_function:
# Function body
# ...
jr $ra # Return to caller
# Calling a function
.text
main:
jal my_function # Call function
# Execution continues here after return
# Simple example: function that adds 5
add_five:
addi $v0, $a0, 5 # $v0 = $a0 + 5
jr $ra # Return
# Calling add_five
li $a0, 10 # Argument = 10
jal add_five # Call function
# $v0 now contains 15Try It Yourself
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21