Loops

The LOOP instruction

LOOP decrements RCX and jumps to a label while RCX is not zero. It is one instruction, but modern CPUs handle the explicit DEC and JNZ pair faster, so expect to see both styles:

mov rcx, 10 print_loop: ; body here loop print_loop ; rcx = rcx - 1, jump if not zero

The register pattern

The explicit pattern gives you control over the counter and the exit condition:

mov rcx, 10 print_loop: ; body here dec rcx jnz print_loop

Nested loops

Save the outer counter before entering the inner loop, on the stack or in a spare register, and restore it after. RCX is the classic counter, so nested loops must protect it.

Next: The stack

Article author: Arthur Isaev