Assembly Condition
## Assembly Language - Conditional Judgment
Conditional judgment is the cornerstone of program control flow. Assembly language implements if-else, switch and other judgment logic through comparison instructions and conditional jump instructions.
* * *
## CMP - Compare Instruction
`CMP` performs subtraction (dest - src) on two operands, but does not save the result, only updates the flag bits.
Essentially `CMP dest, src` is equivalent to `SUB dest, src` but discards the calculation result.
## Example
; CMP compare instruction example
section.text
global _start
_start:
mov eax,10
cmp eax,10; eax == 10?
; ZF = 1 (equal, result is zero)
; CF = 0 (no borrow)
; SF = 0 (result is non-negative)
mov eax,5
cmp eax,10; eax == 10?
; ZF = 0 (not equal, result is non-zero)
; CF = 1 (borrow: 5 < 10)
mov eax,20
cmp eax,10; eax == 10?
; ZF = 0 (not equal)
; CF = 0 (no borrow: 20 >= 10)
; SF = 0 (result is non-negative: 10 > 0)
mov eax,1
mov ebx,0
int 0x80
* * *
## Conditional Jump Instructions
Conditional jump instructions determine whether to jump based on the status of flag bits. If the condition is met, jump to the target label; otherwise, continue executing the next instruction.
| Instruction | Meaning | Flag Bits Checked | Applicable Scenario |
| --- | --- | --- | --- |
| JE / JZ | Jump if equal / zero | ZF = 1 | Check a == b after `cmp a, b` |
| JNE / JNZ | Jump if not equal / not zero | ZF = 0 | Check a != b after `cmp a, b` |
| JG / JNLE | Jump if greater (signed) | ZF=0 and SF=OF | Signed a > b |
| JGE / JNL | Jump if greater or equal (signed) | SF = OF | Signed a >= b |
| JL / JNGE | Jump if less (signed) | SF != OF | Signed a < b |
| JLE / JNG | Jump if less or equal (signed) | ZF=1 or SF!=OF | Signed a <= b |
| JA / JNBE | Jump if greater (unsigned) | CF=0 and ZF=0 | Unsigned a > b |
| JAE / JNB | Jump if greater or equal (unsigned) | CF = 0 | Unsigned a >= b |
| JB / JNAE | Jump if less (unsigned) | CF = 1 | Unsigned a < b |
| JBE / JNA | Jump if less or equal (unsigned) | CF=1 or ZF=1 | Unsigned a <= b |
> Many instructions have two aliases (such as JE and JZ), which are exactly the same at the machine code level. Which one to use depends on the context: use JE/JNE after comparisons, and JZ/JNZ after checking arithmetic results. This makes the code more readable.
* * *
## Single-branch IF Structure
## Example
; File path: if_demo.asm
; Implementation: if (x > 10) x = 10;
section.data
x dd 15; Test value
limit dd 10
section.text
global _start
_start:
mov eax,; Load x into eax
cmp eax,; x > 10 ?
jle skip_update ; If x <= 10, skip update
mov dword,10; x = 10
skip_update:
; Program continues... (here x is already 10)
mov eax,1
mov ebx,0
int 0x80
* * *
## IF-ELSE Dual-branch Structure
## Example
; File path: if_else_demo.asm
YouTip