execution

Conditional Execution in Assembly

Conditional Execution

Conditional execution in assembly is achieved using conditional jump instructions. These instructions allow branching based on the results of comparisons or arithmetic operations.

Common Conditional Jump Instructions

Example: Comparing Two Numbers

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
    

Example: Looping with Conditional Execution

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
    

Key Notes