Chapter 5

Subprograms


# example subprogram which just prints the newline character

.text

main:

	# Read user input into $s0
	li $v0, 4
	la $a0, prompt
	syscall
	li $v0, 5
	syscall
	move $s0, $v0
	
	# print the value back
	li $v0, 4
	la $a0, result
	syscall
	
	# call the newline print function
	jal print_newline
	
	li $v0, 1
	move $a0, $s0
	syscall
	
	# call the exit subprogram
	# jal = jump and link
	jal exit


.data
prompt: .asciiz "Enter a number: >"
result: .asciiz "Result: "

# Newline subprogram
.text
print_newline:
	li $v0, 4
	la $a0, __pnl_newline
	syscall
	# ra is auto filled with the return address upon jal call
	jr $ra
.data
	__pnl_newline: .asciiz "\n"
	
# Exit subprogram
.text
exit:
	li $v0, 10
	syscall

Subprogram parameters and return values

Params are stored in the $a0...$a4 registers

Return vals are stored in $v0 and $v1


# example subprogram which takes in a parameter, stored in $a0
# printstring subprogram

.text

main:

	# Read user input into $s0
	la $a0, prompt
	jal print_string
	li $v0, 5
	syscall
	move $s0, $v0
	
	# print the value back
	la $a0, result
	jal print_string

    # print the return value, which was stored in $v0
    move $a0, $v0
    li $v0, 1
    syscall
	
	# print the entered number
	li $v0, 1
	move $a0, $s0
	syscall
	
	# call the exit subprogram
	# jal = jump and link
	jal exit

.data
prompt: .asciiz "Enter a number: >"
result: .asciiz "Result: "
	
# print string subprogram
# args:
# $a0 - the string to print
.text
print_string:
	li $v0, 4
	syscall

    li $v0, 26 # dummy return value
	jr $ra
	
# Exit subprogram
.text
exit:
	li $v0, 10
	syscall

Using multiple ASM files

Files can be included via:

.include "myfile.asm"

Which can be anywhere in the program (not in between actual code of course)