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.

The code on this page was assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev