ISA & Assembly

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

      li   t0, 0
      li   t1, 4
loop: add  t0, t0, t1
      addi t1, t1, -1
      bnez t1, loop
  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. Include the addition when t1 = 1.
Practice this topic Back to topic

More ISA & Assembly questions

  1. RISC-V conditional branches (B-type) encode the distance as a 13-bit signed byte offset whose lowest bit is always 0 and not stored. Roughly what range can a branch reach directly?
  2. What does the RISC-V instruction "jal ra, func" do?
  3. Which real instruction executes the RISC-V pseudo-instruction "ret"?
  4. What is the main purpose of defining a calling convention?
  5. In the standard RISC-V calling convention, which registers pass integer arguments and return values?