What is the CMP instruction and how is it related to SUB?
cmp performs a subtraction purely to set the condition flags, then discards the result — it's sub that doesn't modify the destination.
* cmp is a subtract that keeps only the flags — it discards the result and leaves ZF/SF/CF/OF for the next conditional jump to read. *
You almost never want the difference of two values when comparing them; you want to know which is larger or whether they're equal. cmp gives exactly that by setting flags from dest − src without storing anything.
cmp %rbx, %rax # compute %rax - %rbx, set flags only
je equal # ZF=1 → %rax == %rbx
jl less # SF≠OF → %rax < %rbx (signed)
jb below # CF=1 → %rax < %rbx (unsigned)
The AT&T order trap: cmp $5, %rax computes %rax − 5, so jl less jumps when "%rax < 5." Read it as "compare %rax to 5" and the operands fall into place — but beginners constantly reverse it.
Related idioms: prefer test %rax,%rax over cmp $0,%rax for zero checks, and note that cmp %rax,%rax is always "equal" (rarely useful except to deliberately set ZF).
Go deeper:
Felix Cloutier — CMP — CMP subtracts and sets flags exactly like SUB.