A condition in C99 is a question asked to the flags.
jccdelivers the answer, and the target address lands inrip.
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:
; 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 progbitsThe 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:
- unsigned value of the displacement byte from the disassembly listing.
- signed 8-bit offset from the end of the instruction.
- weight of one byte, i.e., 256.
- destination address where execution continues.
- 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—jge6 bytes forward: after this instruction$ripis0x401009, so the target is0x40100f.eb f5— shortjmp: byte0xf5(245) is greater than 127, so by (1) the offset is-11, landing on0x401004.74 06—je(alias ofjz) 6 bytes forward, using the same pattern for thewhileloop.
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:
; 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 00x282hasSF(bit 7) andIF(bit 9) set;ZF,CF, andOFare zero.- The difference
0xFFFFFFFF - 1 = 0xFFFFFFFEhas bit 31 set, soSF = 1. - Signed
-1 - 1 = -2fits inint32_twithout overflow, soOF = 0. - There was no borrow, so
CF = 0; the result is non-zero, soZF = 0. jgchecksZF = 0andSF = OF:1 != 0, so the branch is not taken (as signed values,-1 < 1).jachecksCF = 0andZF = 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:
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:
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
jmpback 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?
Testing a Popular Myth Against CPU Counters
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.
; 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; 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 progbitsThe two files differ only in the loop body, with ITERATIONS set to 100000000. Disassembly shows both control forms:
loop— a singlee2 feinstruction;dec+jnz—ff c9followed by75 fc(objdumpprintsjne, an alias forjnzsharing opcode75).
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:
- average
cycles:ureported byperf stat. - iteration count defined by
ITERATIONS.
Plugging the measurements into (3) gives:
That’s roughly 1.01 cycles per iteration for loop and 1.02 for dec + jnz.
cycles:u— user-mode cycles:100,566,013forloopand101,868,439fordec+jnzacross 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,083forloop(one per iteration) and200,000,087for the pair (two per iteration).ex_ret_ops:u— macro-ops retired: around100,000,000for both, one per iteration. On this core,loopdoes not crack into multiple macro-ops.ex_ret_fused_instr:u— macro-op fusion:99,999,916fordec+jnzand zero forloop. The pair genuinely enters the pipeline as a single fused macro-op.branches:u— roughly100,000,080backward 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:
loophardwires the counter torcx, whereasdecworks with any general-purpose register;loop’s cost varies across microarchitectures, whiledec+jnzare ordinary instructions whose cost is easy to verify withperf 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 100after_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
-
"
jgpicks the wrong branch on unsigned data."
Fact: aftercmp eax, ebxwith0xFFFFFFFFand1,eflagsis0x282 [ SF IF ], and the program exits with2instead of3.
Cause:jgcomparesSFagainstOF, interpreting the top bit as a sign bit; foruint32_t, ordering comes fromCF.
Fix: useja/jae/jb/jbefor unsigned types, andjg/jge/jl/jlefor signed types. -
“Reading the
f5byte ineb f5as an absolute address.”
Fact:$ripat the instruction is0x40100dand afterstepibecomes0x401004, even though the displacement byte is0xf5.
Cause:ebstores a signed 8-bit offset from the next instruction’s address: by (1),0xf5decodes to-11.
Fix: compute the target as$rip + instruction_length + disp8, never from the raw byte value alone. -
“Short
jmpfails to reach its target.”
Fact: when the loop body exceeds 127 bytes (far_jmp_bad.asm):nasmtimes 130 nop inc ecx jmp short .far_checkthe assembler aborts with an error:
textfar_jmp_bad.asm:19: error: short jump is out of rangeCause:
jmp shortencodes a 1-byte displacement, which only reaches-128to+127bytes.
Fix: dropshortand let NASM emit the neare9encoding 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
_startin a standalonesum_even.asmfile, built withnasmandld. - 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
jccinstruction. - Zero counts as even and is included;
20is included as well. The total fits in a single exit-code byte.
Verification criteria.
./build/sum_even; echo $?prints the expected sum.objdump -d -M intel build/sum_evenshows a backward jump with opcodeeb.- 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:
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
20by usingjlinstead ofjle.
Checking against 110 catches both immediately.
Testbed sources, Makefile, and automated tests for this lesson: lessons/08-control-flow.
Summary
$rippoints to the next instruction; a jump simply writes a new address into it.- A short
jmpencodes asebplus a signed 8-bit displacement from the end of the instruction. jcchas no dedicated “greater than” flag: conditions combineZF,SF,CF, andOF.- Signed and unsigned comparisons differ in the
jccchosen, not the register contents. forandwhilelower to a top check, body, counter update, and backwardjmp.- Preferring
dec+jnzoverloopisn’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-dependentloopbehavior.
$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.