Skip to main content
Be Bitwise
x86 AssemblyControl Flow

Loops in Assembly

Loops are conditional jumps pointing backwards. No for, no while keyword — you build every loop out of the same compare-and-jump primitives from the last lesson. Once the pattern clicks, every loop structure becomes a recipe you assemble on demand.

The While Loop Pattern

A while loop checks the condition first, then runs the body:

c
// C while loop
int i = 0;
while (i < 10) {
// body
i++;
}
nasm
; While loop in assembly
xor rcx, rcx ; i = 0
.while_check:
cmp rcx, 10 ; i < 10?
jge .while_done ; if not, exit loop
; --- loop body ---
; (your code here)
; -----------------
inc rcx ; i++
jmp .while_check ; go back to condition check
.while_done:

Recipe: test at the top, jump out on false, run the body, unconditional jump back to the top.

The Do-While Loop Pattern

A do-while loop runs the body first, then checks the condition:

c
// C do-while loop
int i = 0;
do {
// body
i++;
} while (i < 10);
nasm
; Do-while loop in assembly
xor rcx, rcx ; i = 0
.do_top:
; --- loop body ---
; (your code here)
; -----------------
inc rcx ; i++
cmp rcx, 10 ; i < 10?
jl .do_top ; if yes, loop back
; falls through when condition is false

It's the leaner pattern: one jump per iteration (the conditional at the bottom) instead of two. Compilers reshape while loops into this form whenever they can prove the body runs at least once.

Count the jump instructions each version executes for the ten iterations above. The while loop runs jge and jmp on every pass, plus one last jge to leave: 21 jumps. The do-while runs only its jl, ten times, nine of them taken. Every back edge in the graph below is one of those jumps:

The For Loop Pattern

A for loop is a while loop with an initialiser and an update step bolted on:

c
// C for loop
for (int i = 0; i < 10; i++) {
array[i] = 0;
}
nasm
; For loop in assembly (zero out an array of 10 qwords)
lea rdi, [rel array] ; pointer to array
xor rcx, rcx ; i = 0
.for_check:
cmp rcx, 10
jge .for_done
mov qword [rdi + rcx*8], 0 ; array[i] = 0
inc rcx ; i++
jmp .for_check
.for_done:

Or, in the leaner do-while form, assuming the array has at least one element:

nasm
lea rdi, [rel array]
mov rcx, 10 ; counter = 10
.loop:
mov qword [rdi], 0 ; zero current element
add rdi, 8 ; advance pointer by 8 bytes (qword)
dec rcx ; counter--
jnz .loop ; loop if counter != 0
Counting Down is Often Better

Counting down to zero and using jnz (jump if not zero) is a common assembly idiom. When you dec rcx, the Zero Flag is set automatically when rcx reaches 0. This eliminates the need for a separate cmp instruction, saving one instruction per iteration. In tight loops, this matters.

The LOOP Instruction

x86 ships a dedicated LOOP instruction. It decrements RCX and jumps when RCX isn't zero:

nasm
mov rcx, 10 ; loop count
.loop_top:
; --- loop body ---
loop .loop_top ; rcx--, jump if rcx != 0

It comes with serious baggage:

  1. Slow on many Intel cores, where it decodes to several micro-ops and loses badly to dec rcx; jnz. Recent AMD cores run it about as fast as the pair, so the penalty depends on the chip (Agner Fog's instruction tables list the per-CPU numbers).
  2. Hard-wired to RCX. No swapping in another counter.
  3. Short jumps only; the target has to sit within -128 bytes.

You'll spot it in textbooks and ancient code. Modern compilers don't emit it, and seasoned assembly hands give it a wide berth.

Nested Loops

Nested loops mean stashing the outer counter somewhere the inner loop won't trample:

nasm
; Nested loop: outer runs 5 times, inner runs 10 times
mov r12, 5 ; outer counter (any register the inner loop leaves alone)
.outer:
mov rcx, 10 ; inner counter (reset each outer iteration)
.inner:
; --- inner loop body ---
; r12 = outer index, rcx = inner index
; --------------------------
dec rcx
jnz .inner ; inner loop
dec r12
jnz .outer ; outer loop

What matters is that the inner loop never touches r12. Any spare register would do here; r12 only earns its callee-saved status if the loop body calls other functions, because they promise to preserve it while rcx is fair game for them. Reuse rcx for both counters and the outer one dies on the first inner-loop iteration.

Loop with Early Exit (Break)

c
// C loop with break
for (int i = 0; i < len; i++) {
if (array[i] == target) break;
}
nasm
; Search for target in array, break on match
; rdi = array pointer, rsi = length, rdx = target value
xor rcx, rcx ; i = 0
.search:
cmp rcx, rsi ; i < length?
jge .not_found ; if not, target was not found
cmp [rdi + rcx*8], rdx ; array[i] == target?
je .found ; if yes, break out
inc rcx ; i++
jmp .search ; continue searching
.found:
; rcx holds the index where target was found
jmp .done
.not_found:
mov rcx, -1 ; return -1 for not found
.done:

Loop with Continue (Skip)

c
// C loop with continue
for (int i = 0; i < len; i++) {
if (array[i] == 0) continue;
process(array[i]);
}
nasm
; Skip zero elements
xor rcx, rcx
.loop:
cmp rcx, rsi
jge .done
mov rax, [rdi + rcx*8]
test rax, rax ; is array[i] == 0?
jz .skip ; if zero, skip to next iteration
; process rax...
.skip:
inc rcx
jmp .loop
.done:
Security Note: Infinite Loops and Denial of Service

A loop that never terminates consumes CPU indefinitely. If an attacker can control a loop condition (for example, a length field in a network packet), they can force an infinite loop, creating a denial-of-service condition. Always validate loop bounds against maximum expected values, and consider adding iteration limits for safety. In kernel code and interrupt handlers, infinite loops can freeze the entire system.

Practical Example: String Length (strlen)

Walking a null-terminated string until you hit the zero byte is the canonical example:

nasm
; strlen: count bytes until null terminator
; Input: rdi = pointer to null-terminated string
; Output: rax = length (not including the null)
strlen:
xor rax, rax ; length = 0
.check:
cmp byte [rdi + rax], 0 ; is current byte null?
je .done ; if yes, we are done
inc rax ; length++
jmp .check ; check next byte
.done:
ret ; return length in rax
Security Note: Off-By-One in Bounds Checking

Off-by-one errors in loop bounds are one of the most common vulnerability classes. Using jle (less or equal) instead of jl (less than) - or vice versa - can mean the difference between writing within a buffer and writing one byte past its end. That single byte can overwrite a saved frame pointer, a null terminator, or a length field, leading to exploitable conditions. Always carefully consider whether your comparison should be strict (< / jl / jb) or inclusive (<= / jle / jbe).

Loop Optimization: Unrolling

Loop unrolling crams several iterations into one pass, trading code size for fewer branch instructions:

nasm
; Sum rsi qwords at rdi, four per iteration, then mop up the rest
; Output: rax = sum
xor eax, eax ; sum = 0
xor ecx, ecx ; i = 0
mov rdx, rsi
and rdx, -4 ; rdx = length rounded down to a multiple of 4
.unrolled:
cmp rcx, rdx
jae .tail ; unsigned: lengths and indices never go negative
add rax, [rdi + rcx*8] ; element i
add rax, [rdi + rcx*8 + 8] ; element i+1
add rax, [rdi + rcx*8 + 16] ; element i+2
add rax, [rdi + rcx*8 + 24] ; element i+3
add rcx, 4
jmp .unrolled
.tail: ; 0 to 3 leftover elements
cmp rcx, rsi
jae .done
add rax, [rdi + rcx*8]
inc rcx
jmp .tail
.done:

The .tail loop is the part people forget. Without it, a length of 7 either skips the last three elements or, with a careless bound, reads one block past the end of the array. Compilers emit the same structure when they unroll at higher optimisation levels.

What is Next

Conditional jumps aren't the only way to consume flags. Next up: conditional moves (CMOVcc) and conditional set (SETcc). Branching-free decisions, equally useful for keeping pipelines hot and for sidestepping timing leaks.