Course contentsShow
← Computer Science
Lesson 1100 of 2,87225. Computer Architecture FoundationsFree lesson

Conditional Jumps and Branches

Implementing if-statements using conditional jump instructions based on flag registers.

Conditional Jumps and Branches

What you'll learn: How to make decisions in assembly language by jumping to different code locations based on condition flags.

The Core Idea

Remember how you learned about comparison instructions that set flags, and unconditional jumps that always redirect execution? Conditional jumps combine both: they check the CPU's flag registers (like zero, carry, sign, or overflow flags) and jump only if a specific condition is true. Otherwise, execution just continues to the next instruction.

Think of it like a fork in a hiking trail with a signpost. An unconditional jump says "always go left." A conditional jump says "if it's raining (flag is set), go left; otherwise, keep straight."

How If-Statements Work in Hardware

When you write if (x == y) in high-level code, the computer:

  1. Uses a comparison instruction (like CMP) to subtract the values and set flags
  2. Uses a conditional jump instruction to branch based on those flags

For example:

  • JE (Jump if Equal) checks if the zero flag is set
  • JNE (Jump if Not Equal) checks if the zero flag is clear
  • JG (Jump if Greater) checks sign and overflow flags for signed comparisons
  • JA (Jump if Above) checks carry and zero flags for unsigned comparisons
CMP x, y        ; Compare x and y (sets flags)
JE equal_label  ; Jump to equal_label if x == y
; code if not equal
JMP done
equal_label:
; code if equal
done:

Each conditional jump instruction examines specific flag register bits that were set by the previous comparison or arithmetic operation.

Key Takeaway: Conditional jumps implement if-statements by inspecting flag registers and branching to different code locations only when specified conditions are met—this is how hardware makes decisions.