ISA & Assembly

      li   t0, 0
      li   t1, 4
loop: add  t0, t0, t1
      addi t1, t1, -1
      bnez t1, loop

When the RISC-V code above finishes, what is the value in t0?

  1. A4
  2. B10
  3. C6
Show answer and explanation

Answer: B. 10

The loop adds t1 to t0 while decreasing t1 from 4 by one each time. t0 becomes 4, 7, 9 and 10, and when t1 reaches 0, bnez (branch if not zero) no longer branches and the loop exits. The result is 4 + 3 + 2 + 1 = 10. bnez is a pseudo-instruction for "bne t1, zero, loop". Counting down to zero is common because no constant is needed for the comparison.

  • A. The loop runs more than once.
  • B. Correct. 4 + 3 + 2 + 1 = 10.
  • C. The add comes before t1 is decremented, so the first 4 is added too.