ASMSchool - Lesson 4

In this lesson, you will learn a few more instructions and some methods for controlling program flow.

Jump Around! Jump Around! Jump up, jump up and get down! ;-)

The simplest way to control how your program flows is by jump instructions. There are two versions, one being a far jump and one being a short jump. Both can be conditional based on the Carry or Zero Flags. Why is there a short jump when the regular jump instruction will jump anywhere? Well, take a look:

Standard Jump

JP (label)
JP (condition),(label)
When we actually write code that we will assemble, we will be using labels to define sections and loop or jump points. So (label) will just happen to be whatever you named the loop or jump point. A label will be a string of characters, usually A-Z, 0-9, or underscore character, and will end with a "::". For example:

   LD A,$01
   more code here....
   more code here....
   JP Start_Game
A new operand you will notice in the instruction is (condition). This is basically an operand that tells the CPU to perform the jump ONLY IF the condition is true. The conditions are states of the flags Carry and Zero in the F register. These flags are usually set by the previous instruction, although the state of a flag can stay the same if later instructions don't affect that particular flag. Tbe Conditions are:

C, NC, Z, and NZ

Those stand for CARRY, NO CARRY, ZERO, and NOT ZERO. Say you have a variable "LIVES" and you want to make the program jump to some other code when "LIVES" is ZERO. Building on past lessons, here is an example:

   LD HL, LIVES          ;<--(lives is a constant set to a 16-bit address)
   LD A, (HL)            ;<--(gets value at LIVES location)
   CP $00                ;<--(compares A to $00, if = then Z flag set)
   JP Z,Some_Other_Label ;<--(jumps to Some_Other_Label if Z flag is set)
   NOP                   ;<--(cpu would continue here if Z flag was 0)

In the example, the code first loads the address of the variable into HL, which is set by compiler directives elsewhere, I'll explain that in a later lesson. Then the code loads the value at that address into register A. The next instruction Compares A with $00, by subtracting them, and setting the Z flag if A and the $00 operand were equal, or clearing the Z flag if they were not equal. Then finally, the jump instruction looks to see if Z is set and then jumps if it is. This little piece of code is a very simple IF...THEN statement.