Conditional Branches
Conditional Branches
After setting the flags with CMP, you use conditional branch instructions to control program flow. This is how assembly implements if, else, switch, and every other decision-making construct.
B.cond -- Branch if Condition
The syntax is B. followed by a condition code:
| Instruction | Meaning (after CMP a, b) | Use for |
|---|---|---|
B.EQ | a == b | Equality check |
B.NE | a != b | Inequality check |
B.GT | a > b (signed) | Signed greater than |
B.GE | a >= b (signed) | Signed greater or equal |
B.LT | a < b (signed) | Signed less than |
B.LE | a <= b (signed) | Signed less or equal |
B.HI | a > b (unsigned) | Unsigned greater than |
B.LO | a < b (unsigned) | Unsigned less than |
Tip: Use the signed variants (
GT,GE,LT,LE) for most comparisons. Use unsigned variants (HI,LO) when comparing addresses or values that cannot be negative.
As Spock once said, "There are always possibilities." Conditional branches are how the CPU explores them -- choosing a different code path based on the outcome of each comparison.
Implementing if/else
The pattern is: compare, branch over the "else" code, then skip over the "then" code:
CMP X0, #10
B.GT greater // if X0 > 10, jump to "greater"
// else branch (X0 <= 10):
// ... code ...
B done // skip over the "greater" branch
greater:
// then branch (X0 > 10):
// ... code ...
done:
Key insight: Assembly
if/elseis "inside out" compared to high-level code. You branch to skip code, not to run it. The condition inB.GTis the opposite of what you would write as theelsecondition.
Unconditional Branch
B label always jumps to the label:
B skip_this // always jump
// this code is skipped
skip_this:
CBZ and CBNZ
These combine a compare-to-zero and branch in one instruction. They are very common in loops:
CBZ X0, is_zero // Branch if X0 == 0
CBNZ X0, not_zero // Branch if X0 != 0
These do not set flags and do not require a prior CMP instruction -- they test the register directly.
Finding Maximum -- The Pattern
A common pattern for finding the maximum of N values:
MOV X3, X0 // max = first value
CMP X1, X3 // compare second with max
B.LE skip1 // if second <= max, skip
MOV X3, X1 // max = second
skip1:
// repeat for each additional value...
Your Task
Write a program that finds the maximum of three numbers: 17, 42, and 29. Store each in a register, compare them using CMP and conditional branches, and print the maximum (42) followed by a newline.