Flags and Comparison
What are CPU Flags?
CPU flags are special 1-bit registers that indicate the status of the last operation. They're essential for making decisions and implementing control flow in assembly programs. Our compiler supports four main flags:
- Zero (Z): Set when the result of an operation is zero
- Negative (N): Set when the result is negative
- Carry (C): Set when an operation produces a carry or borrow
- Overflow (V): Set when signed arithmetic overflow occurs
The CMP Instruction
The CMP (compare) instruction is used to compare two values by performing a subtraction and updating the flags, but without storing the result. The syntax is:
CMP Rn, <operand>
This performs Rn - operand and sets flags based on the result, but doesn't modify any registers.
Example: Basic Comparison
MOV R0, #10
MOV R1, #5
CMP R0, R1 // Compare R0 with R1 (10 - 5 = 5)
// Z flag: clear (result is not zero)
// N flag: clear (result is positive)
Understanding Flag Behavior
Zero Flag (Z)
The Zero flag is set when two values are equal:
MOV R0, #15
MOV R1, #15
CMP R0, R1 // 15 - 15 = 0
// Z flag is SET (values are equal)
Negative Flag (N)
The Negative flag is set when the first value is less than the second:
MOV R0, #5
MOV R1, #10
CMP R0, R1 // 5 - 10 = -5
// N flag is SET (first value is smaller)
Comparing with Immediate Values
You can also compare a register directly with a constant:
MOV R0, #42
CMP R0, #50 // Compare R0 with 50
// N flag: SET (42 < 50)
// Z flag: CLEAR (42 ≠ 50)
MOV R0, #100
CMP R0, #100 // Compare R0 with 100
// Z flag: SET (equal)
// N flag: CLEAR
Using Flags for Decisions
Flags are primarily used with branch instructions to create conditional logic. After a CMP instruction, you can use conditional branches like:
- BEQ: Branch if Equal (Z flag set)
- BNE: Branch if Not Equal (Z flag clear)
- BGT: Branch if Greater Than
- BLT: Branch if Less Than
Example: Conditional Logic
MOV R0, #25
CMP R0, #18 // Compare with 18
BGT 4 // Branch to line 4 if R0 > 18
MOV R1, #0 // This won't execute
HALT // Line 4: Program ends here
In this example, since 25 > 18, the BGT instruction branches to line 4, skipping the MOV R1, #0 instruction.
Practical Example: Find Maximum
Here's a complete program that finds the maximum of two numbers:
// Find maximum of two numbers
MOV R0, #15 // First number
MOV R1, #23 // Second number
CMP R0, R1 // Compare them
BGT 6 // If R0 > R1, branch to line 6
MOV R0, R1 // Otherwise, R0 = R1 (the max)
// Line 6: R0 now contains the maximum
HALT
Interactive Features
In our compiler, you can:
- View flags in the "Flags" panel - they update in real-time
- Click on any flag to manually toggle its value
- Use Step mode to see exactly when flags change
- Watch flag highlights to identify state changes
Next Steps
Now that you understand flags and comparison, you're ready to learn about branching and control flow, which heavily relies on these concepts to create loops and conditional logic.