A loop is a block of statements that are repeatedly executed until a condition is satisfied.
The assembly language uses JMP
instruction to implement loops. However, the processor set can use the LOOP
instruction to implement loops conveniently.
The following code snippet illustrates how a loop is implemented through JMP
instruction:
mov AL, 5 ; store the number of iteration in ALL1:(loop code)DEC AL ; decrement ALJNZ L1
AL
.AL
, then takes a conditional jump if AL
is not zero.The following code snippet illustrates how a loop is implemented through the loop
instruction:
mov ECX 5 ; store the number of iterations in ECX registerL1:(loop code)loop l1
loop
instruction always extracts the number of iterations from the ECX
register.loop
instruction decrements the value of ECX
and compares it with zero.ECX
is equal to zero, the program jumps to the L1
label; otherwise, the program exits the loop.The following code illustrates the use of loop
instruction using the X86
instruction set to print the first 10 numbers:
section .textglobal _start ;must be declared for using gcc_start: ;tell linker entry pointmov rcx,10 ;loop runs until the value of rcx is 0mov rax, '1' ;rax holds the character that needs to be printedl1: ;loop startsmov [num], rax ;value in rax moved to variable nummov rax, 4 ;4 is the system call number for the write system callmov rbx, 1 ;1 is the file descriptor for the output streampush rcx ;value of rcx pushed to stack and stored here temporarily;rbx, rcx and rdx are arguments to the write system callmov rcx, num ;num moved to rcx, as rcx contains the character that will be printedmov rdx, 1 ;1 is the size (1 byte) of the character that is to be printedint 0x80 ;interrupt that executes the write system call in kernel modemov rax, [num] ;the first character has been output, value of num moved to eaxsub rax, '0' ;converts character in eax to decimalinc rax ;increments decimal value in eax by 1add rax, '0' ;converts decimal back to characterpop rcx ;pops back value of ecx temporarily stored on the stackloop l1 ;loops, value of ecx auto decrementedmov eax,1 ;system call number (sys_exit)int 0x80 ;call kernelsection .bssnum resb 1
rax
register stores the iteration number, and the rcx
register stores the total number of iterations and is initialized to 10.l1
block represents the loop code. At each iteration, the iteration count in the rcx
register is pushed onto the stack. The current value of rax
is moved to rcx
, and a write system call is made, which prints the number on the screen.rax
is incremented, and the iteration count is popped from the stack into the rcx
register. The program then decrements rcx
and jumps to l1
using the loop
command if rcx
is greater than 0.Free Resources