.data array: .space 200 x: .word 5 .text __start:
First load the value of the variable x into a register. Remember that global variables are accessed using the global pointer register.
lw $t0, x($gp)
Do the addition:
addi $t0, $t0, 3
Store the value back. We can leave this step until we need to use $t0 for something else.
sw $t0, x($gp)
We know what the start address of the array is. We need to add a value to obtain the address of array as indexed by the variable x. The value we actually need depends on the size of each element of the array. Let us assume they are words. The value we need to add is thus the value stored in x * 4 bytes.
First we need to get the start address of the array.
addi $t0, $gp, array
Load the value of x into a register, multiply it by 4 and add it to the start address of the array:
lw $t1, x($gp) addi $t1, $t1, $t1 # Double $t1 addi $t1, $t1, $t1 # Double $t1 again addi $t0, $t0, $t1
Put the value 2 into a register. Remember register $zero always holds the value zero.
addi $t1, $zero, 2 # Put 2 into $t1
Finally store 2 into the array element:
sw $t1, 0($t0)
Note that in binary, multiplying by four is the same as shifting left by two bits. Thus we could have replaced this code:
lw $t1, x($gp) addi $t1, $t1, $t1 # Double $t1 addi $t1, $t1, $t1 # Double $t1 again addi $t0, $t0, $t1
with:
lw $t1, x($gp) sll $t1, $t1, 2 # Multiply $t1 by 4 addi $t0, $t0, $t1
First | Previous | Page 2 | Next | Last |
---|