ISA & Assembly

a0 holds the start address of an int (4-byte) array a, and a1 holds an index i. What does the code above load into a2?

slli t0, a1, 2
add  t0, a0, t0
lw   a2, 0(t0)
  1. AThe value of a[4*i]
  2. BThe address of a[i]
  3. CThe value of a[i]
Show answer and explanation

Answer: C. The value of a[i]

Line 1 shifts i left by 2 bits to get 4 × i, line 2 adds it to the array's start address to get the address of a[i], and line 3 loads 4 bytes from there. Each int is 4 bytes, so element i lies 4 × i bytes from the start. The compiler translates C's "a[i]" into exactly this kind of address calculation followed by a load.

  • A. The address is 4 × i bytes ahead, which is element i.
  • B. The final lw loads the value.
  • C. Correct. It loads from start + 4 × i.
Practice this topic Back to topic

More ISA & Assembly questions

  1. Which statement is correct about designs like x86, where an arithmetic instruction such as "add eax, [rbx]" can use a memory value directly?
  2. How do today's high-performance x86 CPUs execute complex instructions internally?
  3. What instructions does the RISC-V M extension add to the base integer instruction set?
  4. What is the main purpose of the RISC-V C extension (compressed instructions)?
  5. When C's "a * b" (multiplying two ints) is compiled for an RV32I CPU without the M extension, what generally happens?