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
mov AL, 5 ; store the number of iteration in AL L1: (loop code) DEC AL ; decrement AL JNZ L1
AL, then takes a conditional jump if
ALis not zero.
The following code snippet illustrates how a loop is implemented through the
mov ECX 5 ; store the number of iterations in ECX register L1: (loop code) loop l1
loopinstruction always extracts the number of iterations from the
loopinstruction decrements the value of
ECXand compares it with zero.
ECXis equal to zero, the program jumps to the
L1label; 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 .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov rcx,10 ;loop runs until the value of rcx is 0 mov rax, '1' ;rax holds the character that needs to be printed l1: ;loop starts mov [num], rax ;value in rax moved to variable num mov rax, 4 ;4 is the system call number for the write system call mov rbx, 1 ;1 is the file descriptor for the output stream push rcx ;value of rcx pushed to stack and stored here temporarily ;rbx, rcx and rdx are arguments to the write system call mov rcx, num ;num moved to rcx, as rcx contains the character that will be printed mov rdx, 1 ;1 is the size (1 byte) of the character that is to be printed int 0x80 ;interrupt that executes the write system call in kernel mode mov rax, [num] ;the first character has been output, value of num moved to eax sub rax, '0' ;converts character in eax to decimal inc rax ;increments decimal value in eax by 1 add rax, '0' ;converts decimal back to character pop rcx ;pops back value of ecx temporarily stored on the stack loop l1 ;loops, value of ecx auto decremented mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel section .bss num resb 1
raxregister stores the iteration number, and the
rcxregister stores the total number of iterations and is initialized to 10.
l1block represents the loop code. At each iteration, the iteration count in the
rcxregister is pushed onto the stack. The current value of
raxis moved to
rcx, and a write system call is made, which prints the number on the screen.
raxis incremented, and the iteration count is popped from the stack into the
rcxregister. The program then decrements
rcxand jumps to
rcxis greater than 0.
View all Courses