Loops repeat an action until a termination condition is reached. This condition can be a counter or the result of an expression's evaluation. MASM 6.0 offers many ways to set up loops in your programs. The following list compares MASM loop structures.
Instructions | Action | |
LOOP | Automatically decrements CX. When CX = 0, the loop ends. The top of the loop cannot be greater than 128 bytes from the LOOP instruction. (This is true for all LOOP instructions.) | |
LOOPE, LOOPZ, LOOPNE, LOOPNZ | Loops while equal (or not equal). Checks CX and a condition. The loop ends when the condition is true. Set CX to a number out of range if you don't want a count to control the loop. | |
JCXZ, JECXZ | Branches to a label only if CX = 0 (ECX on the 80386). Useful for testing condition of CX before beginning loop. If CX = 0 before entering the loop, CX decrements to –1 on the first iteration and then must be decremented 65,535 times before it reaches 0 again. Unlike conditional-jump instructions, which can jump to either a near or a short label under the 80386 or 80486, the loop instructions JCXZ and JECXZ always jump to a short label. | |
Conditional jumps | Acts only if certain conditions met. Necessary if several conditions must be tested. See Section 7.1.2, “Conditional Jumps.” |
The following examples illustrate these loop constructions.
; The LOOP instruction: For 200 to 0 do task
mov cx, 200 ; Set counter
next: . ; Do the task here
.
.
loop next ; Do again
; Continue after loop
; The LOOPNE instruction: While AX is not 'Y', do task
mov cx, 256 ; Set count too high to interfere
wend: . ; But don't do more than 256 times
. ; Some statements that change AX
.
cmp al, 'Y' ; Is it Y or too many times?
loopne wend ; No? Repeat
; Yes? Continue
; Using JCXZ: For 0 to CX do task
; CX counter set previously
jcxz done ; Check for 0
next: . ; Do the task here
.
.
loop next ; Do again
done: ; Continue after loop