6.2 Conditional Jumps

In conditional jumps, the control is transferred to a memory address based on some condition. To use a conditional jump, you need instructions that can alter the flags (set or clear). These instructions can be performing an arithmetic operation or a bitwise operation. The x86 instruction provides the cmp instruction, which subtracts the second operand (source operand) from the first operand (destination operation) and alters the flags without storing the difference in the destination. In the following instruction, if the eax contained the value 5, then cmp eax,5 would set the zero flag (zf=1), because the result of this operation is zero:

cmp eax,5  ; subtracts eax from 5, sets the flags but result is not stored

Another instruction that alters the flags without storing the result is the test instruction. The test instruction performs a bitwise and operation and alters the flags without storing the result. In the following instruction, if the value of eax was zero, then the zero flag would be set (zf=1), because when you and 0 with 0 you get 0:

test eax,eax ; performs and operation, alters the flags but result in not stored

Both cmp and test instructions are normally used along with the conditional jump instruction for decision making. 

There are a few variations of conditional jump instructions; the general format is shown here:

jcc <address>

The cc in the preceding format represents conditions. These conditions are evaluated based on the bits in the eflags register. The following table outlines the different conditional jump instructions, their aliases, and the bits used in the eflags register to evaluate the condition:

Instruction Description Aliases Flags
jz jump if zero je zf=1
jnz jump if not zero jne zf=0
jl jump if less jnge sf=1
jle jump if less or equal jng zf=1 or sf=1
jg jump if greater jnle zf=0 and sf=0
jge jump if greater or equal  jnl sf=0
jc jump if carry jb,jnae cf=1
jnc jump if not carry jnb,jae  .