branching

We now have a JUMP instruction that lets us jump directly to any part of the program.

We now want conditionals — the ability to choose between two outcomes, depending on some condition.

tip

This is exactly like how switches switches have two behaviours based on whether they have marble or hole.

As an example, let’s look at writing a program to behave like our calculator:

  • The user manually sets three pieces of memory: A, B, and op
  • The program checks op
  • If op is 0, calculate A + B
  • If op is 1, calculate A - B

As a program, we could write this as the pseudocode:

if op is 0
then jump to [add]
else jump to [subtract]

add:
  add A to B
  jump to [end]

subtract:
  subtract B from A
  jump to [end]

end:
  // end of program

We know how to implement the ADD, SUBTRACT, and JUMP. But how do we check if op is 0, and branch based on the result?

IFZERO

Let’s define a new instruction. IFZERO checks a specified address, and then:

  • If it’s 0, do nothing.
  • Otherwise, increment the PC, skipping the next instruction.

In other words, the instruction right after an IFZERO only gets triggered if the checked value is zero.

Often, this instruction will be a JUMP. So if this instruction gets hit, then we’ll jump to a different part of the program. Which means that the instruction after that won’t get executed if the checked value was zero, because we’ll have jumped away before we reach it.

This means that IFZERO followed by a JUMP implements the if-then-else pattern:

  • If this thing is true,
  • then perform an action,
  • else perform a different action.

So let’s write the assembly code for our calculator:

00 IFZERO #0 // #0 is op
01 JUMP 03
02 JUMP 04
---
03 ADD #1 #2 // #1 is A, #2 is B
04 JUMP 07
---
05 SUB #1 #2
06 JUMP 07
---
07 END // end of program

implementation

coming soon
We’re still working on this part of the tutorial — come back later!

continue