TExcelTAD
Home › x86-64 Assembly › Loops

Loops

A loop is just a conditional jump backwards. There are no special loop constructs to learn — only a few patterns that make while, for and do … while easy to write and fast to run.

Counting up: a for loop

for (i = 1; i <= 100; i++) sum += i; needs a counter, a body, an increment and a test. Placing the test at the bottom of the loop saves one jump per iteration:

nasm · try it yourself
section .text
global _start
_start:
    xor eax, eax                ; sum = 0
    mov ecx, 1                  ; i = 1
.loop:
    add rax, rcx                ; sum += i
    inc ecx                     ; i++
    cmp ecx, 100
    jle .loop                   ; while i <= 100

    mov rdi, rax
    call print_uint             ; 1 + 2 + ... + 100

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
5050

Note: A bottom-tested loop always runs its body at least once. If the count could be zero, check it once before entering the loop (test ecx, ecx / jz .done), which is exactly what compilers do.

Counting down

Counting down to zero is even shorter, because dec sets the zero flag by itself and no cmp is needed. Use a callee-saved register such as rbx when the loop body calls a function:

nasm · try it yourself
section .text
global _start
_start:
    mov ebx, 5                  ; counter (survives print_uint)
.countdown:
    mov edi, ebx
    call print_uint
    dec ebx                     ; sets ZF when it reaches 0
    jnz .countdown

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
5
4
3
2
1

The loop instruction

x86 has a dedicated instruction: loop label decrements rcx and jumps if it isn't zero yet — dec rcx + jnz in one. It is compact, but on most modern CPUs it is slower than the two-instruction version, so compilers never emit it. It also only works with rcx, which syscall and most functions destroy.

nasm · try it yourself
section .data
star:   db "*"
newline: db 10

section .text
global _start
_start:
    mov ecx, 8                  ; print 8 stars
.again:
    push rcx                    ; syscall destroys rcx: save it
    mov eax, 1
    mov edi, 1
    mov rsi, star
    mov edx, 1
    syscall
    pop rcx
    loop .again                 ; rcx--, jump if rcx != 0

    mov eax, 1                  ; finish the line
    mov edi, 1
    mov rsi, newline
    mov edx, 1
    syscall

    mov eax, 60
    xor edi, edi
    syscall
********

while loops: unknown number of iterations

When you don't know how often the loop runs, test the condition at the top. The Collatz sequence repeats "if n is even, n = n / 2, else n = 3n + 1" until it reaches 1 — nobody has proven it always gets there, but it does for every number tried so far. Let's count the steps for 27:

nasm · try it yourself
section .text
global _start
_start:
    mov eax, 27                 ; n
    xor edi, edi                ; steps = 0
.while:
    cmp rax, 1
    je .done                    ; while (n != 1)
    inc rdi                     ; steps++
    test al, 1
    jnz .odd
    shr rax, 1                  ; even: n = n / 2
    jmp .while
.odd:
    lea rax, [rax + rax*2 + 1]  ; odd: n = 3n + 1
    jmp .while
.done:
    call print_uint             ; rdi = steps

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
111

shr rax, 1 shifts all bits right by one, which divides an unsigned number by 2 (shifts are in a later lesson).

Nested loops

A loop inside a loop needs a separate counter for each level. This prints a small triangle; the inner loop fills a line buffer with row stars, and the outer loop prints one line per row:

nasm · try it yourself
section .bss
line:   resb 16

section .text
global _start
_start:
    mov r12d, 1                 ; row = 1
.outer:
    xor ecx, ecx                ; col = 0
.inner:
    mov byte [line + rcx], '*'
    inc ecx
    cmp ecx, r12d
    jb .inner                   ; while col < row
    mov byte [line + rcx], 10   ; end the line

    mov eax, 1
    mov edi, 1
    mov rsi, line
    lea edx, [r12d + 1]         ; row stars + newline
    syscall

    inc r12d
    cmp r12d, 5
    jbe .outer                  ; rows 1..5

    mov eax, 60
    xor edi, edi
    syscall
*
**
***
****
*****

break and continue

  • break = jump to the label after the loop (jmp .done, or a conditional jump straight there).
  • continue = jump to the loop's increment/test part.

Common mistakes

Mistake Symptom
Counter in rcx, rax, rdx, rsi, rdi, r8–r11 while calling functions or syscall the counter changes unexpectedly; infinite loop or crash
cmp / jl used for unsigned counts above 2^31 loop ends too early or never
forgetting that a bottom-tested loop runs once wrong result for a count of 0
writing to memory with the wrong size (mov [buf + rcx], eax) overwrites neighbouring bytes

Test yourself

What does loop .top do?

  1. Jumps if rax is zero
  2. Decrements rcx and jumps to .top if rcx is not zero
  3. Repeats the next instruction rcx times
  4. Pushes the address of .top

Why do the examples keep loop counters in rbx or r12 when the body calls print_uint?

  1. Those registers are faster
  2. The calling convention guarantees functions preserve them
  3. print_uint needs rcx free
  4. rbx is the only register that can count

Why can counting down to zero save an instruction?

  1. Because dec sets the zero flag, so no cmp is needed before jnz
  2. Because zero is faster
  3. Because loop requires it
  4. It doesn't