Lab Report On Adding A+b C Using Functions
Lab Report On Adding A+b C Using Functions
Mohamed Hiba
CSC21000
Mar 19 ℎ
= +
using only the specified registers ($a0, $a1, $a2, $ra) and a manual return. In MARS , we normally cannot write directly to the PC
(e.g.\ addi $pc,$zero,$ra does not exist). Instead, one uses jr $ra to return.
Example Code
.text
main:
# 1) Put some hard-coded values into a0 and a1
addi $a0, $zero, 1 # a = 1
addi $a1, $zero, 2 # b = 2
main_return:
# Now c = a+b is sitting in $a2.
li $v0, 1 # syscall code 1 = print integer
add $a0, $zero, $a2 # or move $a0, $a2
syscall
# Exit program
li $v0, 10
syscall
do_sum:
add $a2, $a0, $a1 # c = a+b
# Return to whatever address is in $ra. (return to the caller)
jr $ra
Key Points
1. Registers
$a0 holds parameter a
$a1 holds parameter b
$a2 is used for the result c
$ra is used for the “return address”
2. No jal Allowed
Normally, we would call a function with jal do_sum (which both jumps and sets $ra automatically). Since “no jal ” is
allowed, we had to:
Manually load $ra with the address where we want to return.
Use a plain j do_sum instead of jal do_sum .
3. Returning by jr $ra
Standard MIPS uses jr $ra to branch back to the address in $ra (jump regester to the address at $ra ) by that it returns
to the caller.
4. Hard-Coded Parameters
This example just uses constants ( addi $a0,$zero,1 and same with $a1 )
𝑐
𝑡
𝑎
𝑏