Skip to content
BetterDL

Conditional branch

Also called: conditional jump, JZ, jump if zero, branch if zero, branch taken

A jump that happens only when a condition holds, such as Tiny8's JZ, which jumps only when the zero flag is 1.

A conditional branch is a jump instruction with a test. If the condition holds, the PC is loaded with the target (the branch is taken). If not, nothing happens and the program carries on to the next word (not taken).

Tiny8's conditional branch is JZ a (opcode 6): if the zero flag is 1, PC ← a.

Paired with SUB, it makes comparisons. To test whether two values are equal, subtract one from the other; if the result is 0, Z = 1 and JZ jumps. It also ends loops: count down with SUB, and JZ out when the count hits 0.

In hardware, JZ's E1 sets PCsrc = 1 and drives LdPC with Z. When Z = 0, no signal is asserted, but the cycle still passes. So JZ takes 5 cycles taken or not.

A not-taken JZ doesn't add 1 to the PC again. The PC was already advanced during fetch, so it already points at the next instruction.

Worked example

Example

Taken and not taken

Tiny8 program: 0: LOAD C (1C), 1: SUB D (4D), 2: JZ 5 (65), 3: LOAD D (1D), 4: HALT (00), 5: LOAD C (1C), 6: HALT (00).

  1. 1.

    Case 1, M[C] = 6, M[D] = 6: SUB gives 0, so Z = 1. JZ is taken: PC = 5. LOAD C gives ACC = 6, then HALT at 6.

  2. 2.

    Case 2, M[C] = 6, M[D] = 2: SUB gives 4, so Z = 0. JZ is not taken: PC stays 3. LOAD D gives ACC = 2, then HALT at 4.

  3. 3.

    Either way the JZ itself took 5 cycles.

Common mistakes

  • Thinking a not-taken JZ adds 1 to the PC. Fetch already did that.

  • Checking Z after a STORE as if STORE set it. STORE leaves Z alone, so Z comes from the last LOAD, ADD or SUB.

  • Expecting a not-taken branch to be faster in Tiny8. It still takes 5 cycles.

Practice Conditional branch

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Conditional branch is taught in Basic CPU / Computer Architecture.