Cpu Work (2)

Published: (February 2, 2026 at 02:11 AM EST)
3 min read
Source: Dev.to

Source: Dev.to

How CPUs Implement Loops and Conditions

Even though a CPU only performs arithmetic on numbers, it can still execute loops and conditional branches thanks to special branch instructions that change the flow of execution.

Conditional Jump (JZ)

A typical conditional‑jump instruction is JZ (jump if zero). It transfers control to a labeled address when a specific flag (the zero flag) is set.

LOAD A, 1
LOAD B, 1

CMP A, B        ; compare A and B
JZ exit         ; jump to `exit` if the comparison result is zero
STOREM A, 0     ; store register A to memory
exit:
HALT

What does JZ check?

JZ does not examine the label itself. It looks at the Zero flag (Z), which is set by the preceding CMP instruction. If the flag is true (1), the CPU jumps to the address marked by the label.

Flags Updated by CMP

The CMP (compare) instruction subtracts one operand from the other without storing the result; it only updates status flags:

FlagMeaning
Z (Zero)Set to 1 if the subtraction result is zero
N (Negative)Set to 1 if the result is negative

In real CPUs these flags reside in a status/flags register; in a simulation they can be stored in a simple struct.

Loop Example

A loop can be built from a conditional jump (JZ) and an unconditional jump (JMP).

LOAD A, 4
LOAD B, 1
LOAD C, 1

loop:
    SUB A, B          ; A = A - B
    CMP A, C
    JZ exit           ; if A == C, exit loop
    JMP loop          ; otherwise repeat
exit:
    HALT
  • JZ performs the conditional exit.
  • JMP unconditionally jumps back to the start of the loop.

If the zero flag is not set, execution falls through to JMP, which always transfers control back to loop.

Implementation of CMP (simulation)

// Subtract operandB from operandA and set flags
int temp = reg.r[inst.operandA] - reg.r[inst.operandB];
flag.zero     = (temp == 0);
flag.negative = (temp < 0);
programCounter++;   // advance to next instruction

Key rule: CMP must not modify any registers or memory; it only updates the flags.

Other Jump Instructions

Depending on the CPU design, additional conditional jumps may be available, such as:

  • JG – jump if greater (Z = 0 and N = 0)
  • JL – jump if less (N = 1)
  • JNZ – jump if not zero (Z = 0)

These use the same flag values set by CMP or similar instructions.

Mapping High‑Level Code to CPU Branches

Consider the following C‑style conditional:

int valueA = 2;
int valueB = 3;

if (valueA == valueB) {
    // do stuff
}

At the machine level the compiler typically generates:

  1. CMP valueA, valueB – sets flags based on valueA - valueB.
  2. JZ label – jumps to the block if the zero flag is set (i.e., the values are equal).

Thus, even complex high‑level constructs boil down to a series of flag‑setting comparisons and branch instructions.

Back to Blog

Related posts

Read more »