JMP and LOOP Instructions


JMP Instruction
The JMP instruction causes an unconditional transfer, the offset of destination (from the start of the code segment) is moved into the instruction pointer, causing execution to continue at the new location.

LOOP Instruction
The LOOP instruction repeats a block of statements a specific number of times. The loop destination must be within –128 to +127 bytes of the current location counter. ECX is automatically used as a counter and is decremented each time the loop repeats. The execution of the LOOP instruction involves two steps:
  1. It subtracts 1 from ECX.
  2. It compares ECX to zero. If ECX ≠ 0, a jump is taken to the label identified by destination. Otherwise, if ECX == 0, no jump takes place and control passes to the instruction following the loop.
 Compare and Jump  Loop  Double Loops
 ; 10 × 5 = 
 ;  10+10+10+10+10

 X = 10
 Y =  5
 .code
     mov   eax, 0
     mov   ecx, Y
 L1: cmp   ecx, 0
     je    L2
     add   eax, X
     dec   ecx
     jmp   L1
 L2: call  WriteInt
 ; 10 × 5 = 
 ;  10+10+10+10+10

 X = 10
 Y =  5  
 .code
     mov   eax, 0
     mov   ecx, Y
 L1: add   eax, X
     loop  L1
     call  WriteInt
 ; 10 × 3 × 3 =
 ;  (10+10+10) + (10+
 ;   10+10) + (10+10+10)
 X = 10
 Y =  3
 Z =  3
 .data
 save  DWORD  ?
 .code
     mov   eax, 0
     mov   ecx, Z
 L1: mov   save, ecx
     mov   ecx, Y
 L2: add   eax, X
     loop  L2
     mov   ecx, save
     loop  L1
     call  WriteInt
 Output  Output  Output