On this page

A condition in C99 is a question asked to the flags. jcc delivers the answer, and the target address lands in rip.

Branching looks like a language feature: if, for, while. None of those words exist in machine code. There is only a comparison, status flags, and an instruction that either overwrites $rip or leaves it untouched. In this lesson, I build two testbeds—a loop written in two forms, and a comparison of 0xFFFFFFFF against 1 under signed and unsigned conditions—and then inspect the jumps in objdump and GDB.

Mental Model: A Condition Is an Address

What it looks like in C99 What happens in hardware
if (a > b) { ... } cmp sets the flags; jcc either jumps past the body or falls through into it
for (i = 0; i < n; i++) Top-of-loop check at a label, loop body, inc on the counter, and a backward jmp to the check
while (n > 0) Same top check, except the counter counts down with dec
int32_t and uint32_t compare the same way Signed and unsigned comparisons are different jcc instructions reading the exact same flags
goto done; jmp with a relative offset: short eb or near e9

Key idea: the CPU has no concept of a “loop.” It only knows that after each instruction $rip points to the next one, and that certain instructions can write a different value into $rip. A loop is simply a jmp that sends $rip backward.

$rip, jmp, and the eb Byte

RIP-relative addressing is why an objdump listing shows a couple of offset bytes next to a jump instead of an absolute address.

Let’s walk through the loop in sum_loop.asm:

sum_loop.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; sum_loop.asm — the same loop counting up (for) and down (while); the sum
; is returned via exit code. Checkpoints after_for and after_while are read by GDB.

default rel

%define SYS_EXIT 60
%define FOR_LIMIT 10
%define WHILE_START 10

section .text
    global _start

_start:
    xor eax, eax
    xor ecx, ecx

.for_check:
    cmp ecx, FOR_LIMIT
    jge after_for
    add eax, ecx
    inc ecx
    jmp .for_check

after_for:
    mov ecx, WHILE_START

.while_check:
    test ecx, ecx
    jz after_while
    add eax, ecx
    dec ecx
    jmp .while_check

after_while:
    ; syscall: exit(sum)
    mov edi, eax
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

The disassembler shows both backward jumps fitting into a single displacement byte:

  401004:	83 f9 0a             	cmp    ecx,0xa
  401007:	7d 06                	jge    40100f <after_for>
  401009:	01 c8                	add    eax,ecx
  40100b:	ff c1                	inc    ecx
  40100d:	eb f5                	jmp    401004 <_start.for_check>
...
  401014:	85 c9                	test   ecx,ecx
  401016:	74 06                	je     40101e <after_while>
  401018:	01 c8                	add    eax,ecx
  40101a:	ff c9                	dec    ecx
  40101c:	eb f6                	jmp    401014 <after_for.while_check>

A short jump stores its displacement in a single signed byte:

disp8={b,b<128b−28,b≥128,target=ripnext+disp8 \begin{aligned} \mathrm{disp8} &= \begin{cases} b, & b < 128 \\ b - 2^8, & b \ge 128 \end{cases}, \qquad \\[4pt] \text{target} &= \text{rip}_{\text{next}} + \mathrm{disp8} \end{aligned}
where
bb
unsigned value of the displacement byte from the disassembly listing.
disp8\mathrm{disp8}
signed 8-bit offset from the end of the instruction.
282^8
weight of one byte, i.e., 256.
target\text{target}
destination address where execution continues.
ripnext\text{rip}_{\text{next}}
address of the instruction immediately following the current one.

The easiest way to read 0xf5 is as an ordinary signed int8_t: in two’s complement that’s -11, and the CPU adds that int8_t to the $rip of the next instruction.

  • 83 f9 0a — cmp ecx, 10: three bytes, because the second operand is an immediate rather than a register.
  • 7d 06 — jge 6 bytes forward: after this instruction $rip is 0x401009, so the target is 0x40100f.
  • eb f5 — short jmp: byte 0xf5 (245) is greater than 127, so by (1) the offset is -11, landing on 0x401004.
  • 74 06 — je (alias of jz) 6 bytes forward, using the same pattern for the while loop.

In GDB you can watch this step by step: $rip on the jmp instruction is 0x40100d, the bytes at that address are 0xeb 0xf5, and after stepi the register holds 0x401004.

Breakpoint 1, _start.for_check () at sum_loop.asm:20
20	    cmp ecx, FOR_LIMIT
...
rip            0x40100d            0x40100d <_start.for_check+9>
0x40100d <_start.for_check+9>:	0xeb	0xf5
...
rip            0x401004            0x401004 <_start.for_check>

One crucial detail: when stopped at an instruction, $rip points to the instruction itself, whereas while executing it the CPU uses the address of the next instruction as the base for the offset. The target is therefore always calculated from $rip + instruction_length, not from the label’s own address.

  0x401004  <_start.for_check>   ◄──────┐
  ...                                   │ disp8 = 0xf5 (-11)
  0x40100d  eb f5  jmp .for_check       │
  0x40100f  rip_next (base address) ────┘

jcc: One Table of Conditions

The jcc family has no dedicated “greater than” flag: every condition is composed from the four RFLAGS bits (lesson 07).

Instruction Short opcode Taken when C99 equivalent
je / jz 74 ZF = 1 a == b
jne / jnz 75 ZF = 0 a != b
jg 7f ZF = 0 and SF = OF a > b, signed
jge 7d SF = OF a >= b, signed
jl 7c SF ≠ OF a < b, signed
jle 7e ZF = 1 or SF ≠ OF a <= b, signed
ja 77 CF = 0 and ZF = 0 a > b, unsigned
jae 73 CF = 0 a >= b, unsigned
jb 72 CF = 1 a < b, unsigned
jbe 76 CF = 1 or ZF = 1 a <= b, unsigned
js 78 SF = 1 negative result
jns 79 SF = 0 non-negative result
jo 70 OF = 1 signed overflow
jno 71 OF = 0 no signed overflow

Short opcodes 70–7f take two bytes including the displacement. If the target is farther than 127 bytes away, NASM switches to the near form 0f 8x with a 32-bit displacement—more on that in Common Pitfalls.

Signed vs. Unsigned on Identical Bytes

The cmp_jg_ja.asm testbed compares 0xFFFFFFFF and 1 in both ways:

cmp_jg_ja.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; cmp_jg_ja.asm — identical bytes 0xFFFFFFFF and 1: signed jg does not take
; the branch, unsigned ja does. Bit 0 = jg, bit 1 = ja.

default rel

%define SYS_EXIT 60

section .text
    global _start

_start:
    mov eax, -1
    mov ebx, 1
    xor r8d, r8d

    cmp eax, ebx
    jg signed_taken
    jmp signed_end

signed_taken:
    or r8d, 1

signed_end:
    cmp eax, ebx
    ja unsigned_taken
    jmp unsigned_end

unsigned_taken:
    or r8d, 2

unsigned_end:
    ; syscall: exit(bits)
    mov edi, r8d
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits
  40100d:	39 d8                	cmp    eax,ebx
  40100f:	7f 02                	jg     401013 <signed_taken>
  401011:	eb 04                	jmp    401017 <signed_end>
...
  401017:	39 d8                	cmp    eax,ebx
  401019:	77 02                	ja     40101d <unsigned_taken>
  40101b:	eb 04                	jmp    401021 <unsigned_end>

Both cmp instructions are byte-for-byte identical; only the conditional jump differs. Inspecting GDB at unsigned_taken reveals the flag state:

Breakpoint 1, unsigned_taken () at cmp_jg_ja.asm:31
31	    or r8d, 2
eflags         0x282               [ SF IF ]
r8             0x0                 0
  • 0x282 has SF (bit 7) and IF (bit 9) set; ZF, CF, and OF are zero.
  • The difference 0xFFFFFFFF - 1 = 0xFFFFFFFE has bit 31 set, so SF = 1.
  • Signed -1 - 1 = -2 fits in int32_t without overflow, so OF = 0.
  • There was no borrow, so CF = 0; the result is non-zero, so ZF = 0.
  • jg checks ZF = 0 and SF = OF: 1 != 0, so the branch is not taken (as signed values, -1 < 1).
  • ja checks CF = 0 and ZF = 0: both hold, so the branch is taken (as unsigned values, 4294967295 > 1).

The testbed exits with 2: only the ja bit fired. Replacing ja with jg makes the program return 0, which is right for a signed comparison—and wrong for an unsigned one.

In C99, that same distinction shows up in the operand types rather than the operator:

Expression Operand type Instruction
a > b int32_t jg
a > b uint32_t ja
a >= b int32_t / uint32_t jge / jae
a < b int32_t / uint32_t jl / jb
a <= b int32_t / uint32_t jle / jbe

The compiler does not store signedness inside a register. It picks the jcc instruction at code-generation time, and the CPU reads the exact same flags later at runtime.

Unrolling for and while

Both loops in sum_loop.asm compute a sum, counting in opposite directions. In C99:

c
int32_t sum = 0;

for (int32_t i = 0; i < 10; i++) {
    sum += i;
}

int32_t n = 10;
while (n > 0) {
    sum += n;
    n--;
}

The first loop adds 0 through 9; the second adds 1 through 10:

∑i=09i=9⋅102=45,∑n=110n=10⋅112=55,45+55=100. \begin{aligned} \sum_{i=0}^{9} i &= \frac{9 \cdot 10}{2} = 45, \\[2pt] \sum_{n=1}^{10} n &= \frac{10 \cdot 11}{2} = 55, \end{aligned} \\[2pt] 45 + 55 = 100.

In assembly, both share the same four-part structure:

  • counter initialization before the top label;
  • condition check at the top label;
  • loop body updating the counter;
  • unconditional jmp back to the check.

Only the check and counter direction differ: cmp ecx, 10 plus jge for for, and test ecx, ecx plus jz for while. Because the check precedes the body, zero iterations work properly: when FOR_LIMIT = 0, execution jumps straight to after_for.

The loop layout is straightforward. That leaves one separate question: what does the backward branch itself cost, and does the dedicated loop instruction actually beat dec + jnz?

This is a standalone mini-experiment rather than a continuation of jcc: the question here isn’t where to jump, but how much loop control itself costs. loop decrements rcx and jumps if non-zero in a single instruction.

On paper that looks cheaper than dec + jnz, yet the real cost depends on what a specific core decodes each form into: macro-ops and instruction fusion. I measure it using two empty-body benchmarks: with no body work, only loop-control overhead remains. The numbers below were captured on an AMD Ryzen 7 7840H (Zen 4); on a different core, you should re-measure.

loop_bench.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; loop_bench.asm — empty body with loop: measures loop-control cost alone.
; 100,000,000 iterations; perf stat counts cycles and macro-ops.

default rel

%define SYS_EXIT 60
%define ITERATIONS 100000000

section .text
    global _start

_start:
    mov ecx, ITERATIONS

.loop:
    loop .loop

    ; syscall: exit(0)
    xor edi, edi
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits
dec_bench.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; dec_bench.asm — same empty body, but dec updates the counter and jnz jumps.
; Paired with loop_bench.asm at the same iteration count.

default rel

%define SYS_EXIT 60
%define ITERATIONS 100000000

section .text
    global _start

_start:
    mov ecx, ITERATIONS

.loop:
    dec ecx
    jnz .loop

    ; syscall: exit(0)
    xor edi, edi
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

The two files differ only in the loop body, with ITERATIONS set to 100000000. Disassembly shows both control forms:

  • loop — a single e2 fe instruction;
  • dec + jnz — ff c9 followed by 75 fc (objdump prints jne, an alias for jnz sharing opcode 75).
  401005:	e2 fe                	loop   401005 <_start.loop>
...
  401005:	ff c9                	dec    ecx
  401007:	75 fc                	jne    401005 <_start.loop>

Note. The ex_ret_ops:u and ex_ret_fused_instr:u counters are specific to AMD Zen 4 (the AMD PMU). On Intel CPUs these events have different names (uops_retired.*), so you will need to rerun the benchmark with your CPU’s event names; numbers from this section do not transfer across microarchitectures.

Running perf with perf stat -r 10 runs each testbed ten times and reports the mean and variance:

$ perf stat -r 10 -e cycles:u,instructions:u,ex_ret_ops:u,ex_ret_fused_instr:u,branches:u ./build/loop_bench
 Performance counter stats for './build/loop_bench' (10 runs):

       100,566,013      cycles:u                                              ( +-  0.08% )
       100,000,083      instructions:u                                        ( +-  0.00% )
       100,023,289      ex_ret_ops:u                                          ( +-  0.00% )
                 0      ex_ret_fused_instr:u
       100,000,080      branches:u                                            ( +-  0.00% )

       0.074490512 +- 0.000205471 seconds time elapsed  ( +-  0.28% )

$ perf stat -r 10 -e cycles:u,instructions:u,ex_ret_ops:u,ex_ret_fused_instr:u,branches:u ./build/dec_bench
 Performance counter stats for './build/dec_bench' (10 runs):

       101,868,439      cycles:u                                              ( +-  0.49% )
       200,000,087      instructions:u                                        ( +-  0.00% )
       100,024,922      ex_ret_ops:u                                          ( +-  0.00% )
        99,999,916      ex_ret_fused_instr:u                                  ( +-  0.00% )
       100,000,084      branches:u                                            ( +-  0.00% )

       0.075507552 +- 0.000408412 seconds time elapsed  ( +-  0.54% )

The cost of one iteration is the mean cycle count divided by the iteration count:

cycles/iter=CN \text{cycles/iter} = \frac{C}{N}
where
CC
average cycles:u reported by perf stat.
NN
iteration count defined by ITERATIONS.

Plugging the measurements into (3) gives:

loop:100 566 013108≈1.01,dec+jnz:101 868 439108≈1.02. \begin{aligned} \text{loop} &: \frac{100\,566\,013}{10^8} \approx 1.01,\\ \text{dec} + \text{jnz} &: \frac{101\,868\,439}{10^8} \approx 1.02. \end{aligned}

That’s roughly 1.01 cycles per iteration for loop and 1.02 for dec + jnz.

  • cycles:u — user-mode cycles: 100,566,013 for loop and 101,868,439 for dec + jnz across 100,000,000 iterations. The ~1% difference is within run-to-run noise; across repeated runs the sign flips, making the two indistinguishable in cycle count.
  • instructions:u — architectural instructions retired: 100,000,083 for loop (one per iteration) and 200,000,087 for the pair (two per iteration).
  • ex_ret_ops:u — macro-ops retired: around 100,000,000 for both, one per iteration. On this core, loop does not crack into multiple macro-ops.
  • ex_ret_fused_instr:u — macro-op fusion: 99,999,916 for dec + jnz and zero for loop. The pair genuinely enters the pipeline as a single fused macro-op.
  • branches:u — roughly 100,000,080 backward branches, one per iteration.
[dec ecx] + [jnz .loop] ──► (decoder fusion)      ──► 1 macro-op (1 cycle)
[loop .loop]            ──► (single instruction)  ──► 1 macro-op (1 cycle)

Takeaway: the blanket claim that “loop is always slower because it cracks into multiple micro-ops” does not hold on Zen 4. Both variants match on cycles and macro-ops, and loop retires one fewer architectural instruction. Good reasons to prefer dec + jnz still remain, just not speed on this core:

  • loop hardwires the counter to rcx, whereas dec works with any general-purpose register;
  • loop’s cost varies across microarchitectures, while dec + jnz are ordinary instructions whose cost is easy to verify with perf stat. Measurements never transfer blindly between cores.
Under the hood: what the :u suffix means The :u suffix restricts counting to user mode: in this environment perf_event_paranoid = 2, so kernel counters are unavailable without root, and the testbed runs entirely in user space. How perf works is covered in lesson 27.

Verification in the Terminal

Both testbeds are verified by exit status, and intermediate sums via breakpoints:

$ ./build/sum_loop; echo $?
100
$ ./build/cmp_jg_ja; echo $?
2
$ gdb -q --nx -batch -ex 'break after_for' -ex run -ex 'info registers eax' ./build/sum_loop
...
eax            0x2d                45
$ gdb -q --nx -batch -ex 'break after_while' -ex run -ex 'info registers eax' ./build/sum_loop
...
eax            0x64                100

after_for holds the sum from the first loop (45), and after_while holds the total (100). If either breakpoint never triggers, the condition check isn’t placed where control flow expects it.

Common Pitfalls

  1. "jg picks the wrong branch on unsigned data."
    Fact: after cmp eax, ebx with 0xFFFFFFFF and 1, eflags is 0x282 [ SF IF ], and the program exits with 2 instead of 3.
    Cause: jg compares SF against OF, interpreting the top bit as a sign bit; for uint32_t, ordering comes from CF.
    Fix: use ja/jae/jb/jbe for unsigned types, and jg/jge/jl/jle for signed types.

  2. “Reading the f5 byte in eb f5 as an absolute address.”
    Fact: $rip at the instruction is 0x40100d and after stepi becomes 0x401004, even though the displacement byte is 0xf5.
    Cause: eb stores a signed 8-bit offset from the next instruction’s address: by (1), 0xf5 decodes to -11.
    Fix: compute the target as $rip + instruction_length + disp8, never from the raw byte value alone.

  3. “Short jmp fails to reach its target.”
    Fact: when the loop body exceeds 127 bytes (far_jmp_bad.asm):

    nasm
        times 130 nop
        inc ecx
        jmp short .far_check

    the assembler aborts with an error:

    text
    far_jmp_bad.asm:19: error: short jump is out of range

    Cause: jmp short encodes a 1-byte displacement, which only reaches -128 to +127 bytes.
    Fix: drop short and let NASM emit the near e9 encoding with a 32-bit displacement.

Lab

Goal. Write a loop that sums even numbers from 0 to 20 inclusive and returns the result via the exit code.

Contract and requirements.

  • Entry point _start in a standalone sum_even.asm file, built with nasm and ld.
  • Accumulate the sum in a register; counting up or down is your choice.
  • Include a backward jump to the check and exit the loop with a jcc instruction.
  • Zero counts as even and is included; 20 is included as well. The total fits in a single exit-code byte.

Verification criteria.

  1. ./build/sum_even; echo $? prints the expected sum.
  2. objdump -d -M intel build/sum_even shows a backward jump with opcode eb.
  3. In GDB at a post-loop label, the accumulator register holds the total and the counter register stopped at the boundary value.
Hints, expected output, and walkthrough

Sum of even numbers from 0 to 20:

2⋅(0+1+⋯+10)=2⋅10⋅112=110 2 \cdot (0 + 1 + \dots + 10) = 2 \cdot \frac{10 \cdot 11}{2} = 110

Exit status 110 fits cleanly in one byte.

Parity check without division: test al, 1 sets ZF on even numbers, after which jnz skips the addition. Alternatively, and eax, 1 followed by comparing with zero.

If the loop counts down from 20 to 0, place the exit check after the body: sub ecx, 2 and jns, so zero still gets added. If counting up, place cmp ecx, 20 before the body, choosing jg or ja to match the counter’s signedness.

Two classic bugs in this exercise:

  • summing every integer and getting 210;
  • dropping 20 by using jl instead of jle.

Checking against 110 catches both immediately.

Testbed sources, Makefile, and automated tests for this lesson: lessons/08-control-flow.

Summary

  1. $rip points to the next instruction; a jump simply writes a new address into it.
  2. A short jmp encodes as eb plus a signed 8-bit displacement from the end of the instruction.
  3. jcc has no dedicated “greater than” flag: conditions combine ZF, SF, CF, and OF.
  4. Signed and unsigned comparisons differ in the jcc chosen, not the register contents.
  5. for and while lower to a top check, body, counter update, and backward jmp.
  6. Preferring dec + jnz over loop isn’t about cycle counts: on Zen 4 both take ~1.01 cycles per iteration with macro-op fusion; the real win is choosing any counter register and avoiding microarchitecture-dependent loop behavior.
Bridge to the Next Lesson
Branching only modifies $rip. The program’s second pointer, $rsp, moves on every push and pop, sitting right above virtual memory with a hard boundary the stack cannot cross. In lesson 09, I unpack rsp, the red zone, and the guard page that catches infinite recursion.