Conditional execution in assembly is achieved using conditional jump instructions. These instructions allow branching based on the results of comparisons or arithmetic operations.
je: Jump if equal (zero flag is set).jne: Jump if not equal (zero flag is not set).jg: Jump if greater (signed).jl: Jump if less (signed).jge: Jump if greater or equal (signed).jle: Jump if less or equal (signed).ja: Jump if above (unsigned).jb: Jump if below (unsigned).This example demonstrates comparing two numbers and branching based on the result.
section .text
global _start
_start:
mov rax, 10 ; Load the first number into rax
mov rbx, 20 ; Load the second number into rbx
cmp rax, rbx ; Compare rax and rbx
jl less ; Jump to 'less' if rax < rbx
jg greater ; Jump to 'greater' if rax > rbx
je equal ; Jump to 'equal' if rax == rbx
less:
; Code for less condition
mov rax, 1 ; System call: exit
xor rdi, rdi
syscall
greater:
; Code for greater condition
mov rax, 60 ; System call: exit
xor rdi, rdi
syscall
equal:
; Code for equal condition
mov rax, 60 ; System call: exit
xor rdi, rdi
syscall
Conditional jumps are commonly used to implement loops.
section .data
counter db 5 ; Initialize counter with 5
section .text
global _start
_start:
mov rbx, 0 ; Initialize sum to 0
mov rsi, counter ; Load counter address
loop_start:
cmp byte [rsi], 0 ; Check if counter is 0
je loop_end ; Exit loop if counter == 0
add rbx, [rsi] ; Add counter value to sum
dec byte [rsi] ; Decrement counter
jmp loop_start ; Repeat loop
loop_end:
mov rax, 60 ; System call: exit
xor rdi, rdi ; Exit code: 0
syscall
cmp to compare two values before conditional jumps.