7

I have a register($t2) that has a randomly generated number which I then multiply by 4. My question is, is it possible to use the value in $t2 as an offset when using the lw instruction?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user2103851
  • 71
  • 1
  • 1
  • 2
  • closing as a duplicate of a newer Q&A, [Load Word in MIPS, using register instead of immediate offset from another register](https://stackoverflow.com/q/74769617), because that one has a clear example of using an immediate constant offset as well as asking about using a register. This Q&A isn't bad at all, and it could just have been closed as a dup of this, but since it was answered nicely we might as well point people at it. Err, I forgot this wasn't originally tagged [assembly], I added that tag so I couldn't dup-hammer it. – Peter Cordes Dec 12 '22 at 18:52
  • 1
    Does this answer your question? [Load Word in MIPS, using register instead of immediate offset from another register](https://stackoverflow.com/questions/74769617/load-word-in-mips-using-register-instead-of-immediate-offset-from-another-regis) – Peter Cordes Dec 12 '22 at 18:52

1 Answers1

11

In MIPS you can use a register, an offset, or the addition of both; but not two registers to form an effective address.

So, if you want to load a word pointed by a single register into, say $t0, you would do:

lw $t0, ($t2)

However if you want to load a word pointed by the effective address $t1 + $t2 into $t0 you would first need to perform the addition and then load the word from memory, e.g.:

addu $t1, $t1, $t2
lw $t0, ($t1)

Take into account that by performing the addition you are loosing $t1 previous value, so you should use some free register as the target of the addition.

gusbro
  • 22,357
  • 35
  • 46
  • 2
    If a register is the offset, then can I use the register as the offset? For instance, `li $t0, #4; lw $t1, $t0($t2);`? Assuming #t2 is some array. –  Apr 13 '17 at 17:12
  • 1
    @Christian: In that case you would issue `lw $t1, 4($t0)`. `$t2` is a register which holds a single value, it cannot be an array (you may be referring to the base address of the array though). – gusbro Apr 18 '17 at 14:53