Bird
0
0

Consider this ARM assembly snippet for a recursive factorial function:

medium📝 Analysis Q13 of 15
ARM Architecture - Subroutines and Stack
Consider this ARM assembly snippet for a recursive factorial function:
factorial:
    CMP R0, #1
    BLE end_factorial
    PUSH {LR}
    SUB R0, R0, #1
    BL factorial
    POP {LR}
    MUL R0, R0, R1
end_factorial:
    MOV R1, R0
    BX LR

What will be the value in R1 after calling factorial with R0 = 3?
A0
B3
C1
D6
Step-by-Step Solution
Solution:
  1. Step 1: Trace the recursive factorial

    The function saves LR, decrements R0, calls factorial recursively, restores LR, then multiplies R0 by R1.
  2. Step 2: Calculate factorial for R0=3

    Call factorial(3): R0=3, not base case, PUSH LR, SUB R0=2, BL factorial(2). factorial(2): PUSH LR, SUB R0=1, BL factorial(1). factorial(1): base case, sets R1=1, returns. factorial(2): POP LR, MUL R0=1 * R1=1 =1, MOV R1=1, return. factorial(3): POP LR, MUL R0=2 * R1=1=2, MOV R1=2, return.
  3. Step 3: Correction

    However, the MUL uses R0 and R1, but R0 was decremented before recursive call, so the multiplication is (n-1) * fact(n-1), which is incorrect for factorial.
  4. Step 4: Final value

    Tracing carefully, the final R1 will be 2, which is incorrect factorial of 3 (should be 6). But the code as given will produce 2.
  5. Final Answer:

    2 -> Option D
Quick Trick: SUB decrements R0 before call; MUL uses decremented R0 causing incorrect factorial [Check carefully]
Common Mistakes:
  • Assuming correct factorial computation (expecting 6)
  • Confusing R0 and R1 values
  • Missing base case return value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More ARM Architecture Quizzes