How to do structs in MIPS assembly

[code title=”View Source Code:” collapse=”true”]
# Learning Objectives:
# Functions, arrays, structures.

############################################
#### C++ Code
############################################

#void DisplayTemps(Temp temps[], int len);
#
#struct Temp {
# int lo;
# int hi;
#};
#
#int main() {
# Temp temps[] = { {40, 74}, {45, 80}, {60, 91} };
#
# DisplayTemps(temps, 3);
#
# return (0);
#}
#
#void DisplayTemp(Temp temps[], int len) {
# cout < < "Listing of (lo, hi) temps:"
# << endl;
# for (int i = 0; i < len; i++) {
# cout << temps[i].lo
# << " "
# << temps[i].hi
# << endl;
# }
#}
###

###########################################
#### MIPS code
###########################################

.data

words: .asciiz "Listing of (lo, hi) temps:n"
somespace: .asciiz " "
newline: .asciiz "n"

temps:
# declare an array of structs that is preloaded with values
.word 40,74 #( Just like a 2d array )
.word 45,80
.word 60,91

.text

main:

#######
addiu $sp, $sp, -4
sw $ra, 0($sp)
S
la $a0, temps # DisplayTemps(temps, 3);
addi $a1, $zero, 3 #
jal DisplayTemps ####

lw $ra, 0($sp)
addiu $sp, $sp, 4
jr $ra

DisplayTemps:

###############

li $v0, 4 # print_string
la $a0, words # " Listing of (lo, hi) temps:"
syscall

# FOR LOOP

la $t0, temps #$t0 holds the address of the 1st element
li $t1, 1 # iterator = 1
#a0 holds the current elements value

for:

bgt $t1, $a1, exitfor # exit if iterator > a1 (len)

li $v0, 1 # print_int
lw $a0, ($t0)
syscall

li $v0, 4 # print_string
la $a0, somespace # " "
syscall

li $v0, 1 # print_int
add $t0, 4 # increment the index
lw $a0, ($t0)
syscall

add $t0, 4 #increment index again
lw $a0, ($t0)

li $v0, 4 # print_string
la $a0, newline # "n"
syscall
#Increment iterator
add $t1, 1

j for

exitfor:

jr $ra

[/code]

Another look at C++ vs. Assembly

This little program is written in both C++ ans MIPS assembly code. It asks the user for their name and age, then repeats the info back to the screen. Notice the manual adjustment of the runtime stack in the assembly version.

C++ and Assembly side by side

These small pieces of code demonstrate the differences between high and low level programming languages.