Exercise 2: Tracing Condition Codes Through a Sequence — Possible Solution ==================================================================== THE SEQUENCE ------------------------------ 1. AND R2, R2, #0 ; R2 becomes 0 2. ADD R2, R2, #7 ; R2 becomes 7 3. LEA R3, LABEL ; R3 becomes LABEL's address (given as negative) 4. ADD R2, R2, #-7 ; R2 becomes 0 TRACE, LINE BY LINE ------------------------------ Line 1 -- AND R2, R2, #0 Result written to R2 is 0 -> condition code set: Z Line 2 -- ADD R2, R2, #7 Result written to R2 is 7 (positive) -> condition code set: P Line 3 -- LEA R3, LABEL LEA writes a register (R3), so it DOES set condition codes, per the chapter's own list of register-writing instructions. The problem states LABEL's computed address, interpreted as a signed value, is negative -> condition code set: N Line 4 -- ADD R2, R2, #-7 R2 (currently 7) + (-7) = 0 -> condition code set: Z FINAL CONDITION CODES ------------------------------ After all four instructions, Z is set (N and P cleared) -- reflecting line 4's result, NOT line 2's ADD R2, R2, #7, even though that was also an addition into R2. WHICH INSTRUCTION'S RESULT DO THEY REFLECT ------------------------------ The final condition codes reflect ONLY the most recent register- writing instruction -- line 4 (ADD R2, R2, #-7) -- exactly per the chapter's own warn-box: "condition codes reflect only the LAST register write." Notably, line 3's LEA (writing to R3, a completely different register than R2) still overwrote the condition codes set by line 2, even though R2 itself wasn't touched by that LEA. This is exactly the trap the warn-box calls out: ANY register write updates N/Z/P, regardless of which register it targets. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly identifies that LEA sets condition codes (since it writes a register), tracks N/Z/P through all four lines using the chapter's own set-on-every-register-write rule, and explicitly calls out that the LEA in line 3 overwrote line 2's flags despite operating on a different register -- the specific gotcha the chapter's warn-box warns about.