Jumps and Loops


The JMP instruction

The JMP instruction is short for jump and it is used to make the processor jump to another part of your program. To illustrate the use of this instruction, here's an extract from an imaginary program containing the jump instruction:
   ...
label1:
   ...
   JMP label1
   ...
The 'label1' is to identify the position to which the jump will go. As soon as the JMP instruction is reached, the processor will return to the instruction following 'label1'. The section of code between the label and the jump instruction will repeat forever.

The LOOP instruction

Sometimes we require that a section of code be repeated a certain number of times. The LOOP instruction reduces the value in the CX register by 1 and if it is not zero it jumps to the label specified after the LOOP instruction. Here's an example of the LOOP instruction:
   ...
   MOV CX,50
label1:
   ...
   LOOP label1
The effect of these instructions is to repeat the instructions between the label and the loop instruction 50 times.

The Compare Command

In assembly language programs it is often necessary to compare two numbers and jump depending on the result. The command used to compare numbers is the CMP instruction. The syntax of the instruction is:This instruction sets the flags according to the result of the compare operation. To do something based on the result of this compare we must use a conditional jump instruction.

Conditional Jumps

The conditional jump instruction will only jump if a certain condition is met in the previous compare instruction. For example, the JE instruction will only jump if the two numbers compared were equal. The format of conditional jumps is similar to the normal 'JMP' instruction. Here is a list of the common conditional jumps:

Procedures: CALL and RET

A procedure is a section of code that can be jumped to from anywhere else in the program. As soon as the procedure has finished, the program will jump back to where it was before the procedure was called. Here's an example:
proc1:  ...
        ; this is the procedure which can be called
        ...
        RET

; the main program
        ...
        CALL proc1
        ...
This is what happens in the above extract: When the CALL instruction in the main program is reached, there is a jump to the start of the procedure, 'proc1'. When the procedure reaches the end, the RET instruction makes it jump back to the instruction just following the CALL instruction. The RET instruction, which stands for 'return', is essential for the procedure to work.
Return Icon Back to main index