0

There is an instruction in MIPS which allows us to load a number from Memory. like this:

.data
array: .word 1,2,3,4

.text
  la $t0, A
  lw $t1, 8($t0)  #will load 3 to $t1

Is there any way to use (the number inside a register) instead of (immediate number)? like:

  li $t2, 8
  lw $t1, $t2($t1)  # again will load 3 to $t1

If not how can I do indexed addressing with two registers?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
amin_tay
  • 42
  • 3
  • No, you will just have to add `$t2` and `$t1` beforehand. – Jester Dec 12 '22 at 11:16
  • Related: [Using a register as an offset](https://stackoverflow.com/q/46879095) discusses the design decision of why this is not possible in a machine instruction or pseudo-instruction. – Peter Cordes Dec 12 '22 at 18:21

1 Answers1

2

MIPS lacks the ability to perform variable offsetting like you described. As Jester explained, you will just have to add $t2 to $t1 like so:

.data
array: .word 1,2,3,4

.text
la $t0,array
li $t2,8    #array[2]

addu $t0,$t0,$t2     #using unsigned arithmetic here. Very important!
lw $t1,0($t0)        #load the 3 into $t1

Remember, pointer arithmetic should always be done with unsigned addition/subtraction, as signed arithmetic instructions may cause an overflow exception (something you don't want in this case.)

puppydrum64
  • 1,598
  • 2
  • 15