# A live coding example done as a recap on functions. # This has a simple function with 1 parameter and a return value .data msg_sum1: .asciiz "Sum 1.. " msg_sum2: .asciiz " = " .text main: # $s0 used for max since we set it before doing the jal # but need it again after the jal # If a function uses $s0 that same function must # push it to the stack and pop it to restore it later # $t0 was used for result since we are not doing another # jal after we set its value so we do not need to worry # about it getting overwritten by another function main__prologue: push $ra push $s0 main__body: li $s0, 10 # int max = 10; move $a0, $s0 # int max = 10; jal sum_to # result = sum_to(max); move $t0, $v0 # $t0 = result li $v0, 4 # printf("Sum 1.. "); la $a0, msg_sum1 syscall li $v0, 1 # printf("%d",max); move $a0, $s0 syscall li $v0, 4 # printf(" = "); la $a0, msg_sum2 syscall li $v0, 1 # printf("%d", result); move $a0, $t0 syscall li $v0, 11 # putchar('\n') li $a0, '\n' syscall li $v0, 0 main__epilog: pop $s0 pop $ra jr $ra sum_to: sum_to__prologue: sum_to__body: li $t0, 0 # sum = 0 li $t1, 1 # i = 1 sum_to__while: bgt $t1, $a0, sum_to__while_end # while (i <= n) add $t0, $t0, $t1 # sum = sum + i addi $t1, $t1, 1 # i++ j sum_to__while sum_to__while_end: move $v0, $t0 # return sum sum_to__epilog: jr $ra