This `want to exit when...' business can be performed by a conditional branch. A conditional branch first evaluates whether a condition is true, then it proceeds in one of two ways. If the condition is, indeed, true, the instruction proceeds to a predetermined location that the programmer can specify. If the condition turns out false, the instruction acts like a normal instruction and let the next instruction (the instruction below it) execute.
Conditions that a conditional branch can check for are mainly whether a flag is set or cleared. Such flags are usually set by another operation that occurs immediately before the conditional branch. For example, in our example, we can modify the code to the following:
ldi r17,32
again: st X+,r16
dec r17
breq notagain
rjmp again
notagain:
In this modified code, we initialize register 17 to 32. Note that this is performed before label again because we only need to set register 17 to 32 once. We also add the dec instruction in the loop to decrease register 17 by one every time the st instruction stores another byte.
The most important instruction is the breq instruction. This instruction checks to see if the Z flag is set. If the Z flag is set by the dec instruction, it means register 17 is decremented to zero. This means we have performed 32 st operations. If the Z flag is set, control is passed to the instruction located at the notagain label. If the Z flag is cleared, the branch does not occur. Instead, the processor executes the instruction below breq, which is the unconditional branch back to label again.