Assembly Language for Beginners

(Jeff_L) #1

1.16 Loops


1.16 Loops


1.16.1 Simple example


x86


There is a specialLOOPinstruction in x86 instruction set for checking the value in registerECXand if it is
not 0, todecrementECXand pass control flow to the label in theLOOPoperand. Probably this instruction
is not very convenient, and there are no any modern compilers which emit it automatically. So, if you see
this instruction somewhere in code, it is most likely that this is a manually written piece of assembly code.


In C/C++ loops are usually constructed usingfor(),while()ordo/while()statements.


Let’s start withfor().


This statement defines loop initialization (set loop counter to initial value), loop condition (is the counter
bigger than a limit?), what is performed at each iteration (increment/decrement) and of course loop body.


for (initialization; condition; at each iteration)
{
loop_body;
}


The generated code is consisting of four parts as well.


Let’s start with a simple example:


#include <stdio.h>


void printing_function(int i)
{
printf ("f(%d)\n", i);
};


int main()
{
int i;


for (i=2; i<10; i++)
printing_function(i);

return 0;
};


Result (MSVC 2010):


Listing 1.162: MSVC 2010

_i$ = -4
_main PROC
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _i$[ebp], 2 ; loop initialization
jmp SHORT $LN3@main
$LN2@main:
mov eax, DWORD PTR _i$[ebp] ; here is what we do after each iteration:
add eax, 1 ; add 1 to (i) value
mov DWORD PTR _i$[ebp], eax
$LN3@main:
cmp DWORD PTR _i$[ebp], 10 ; this condition is checkedbefore each iteration
jge SHORT $LN1@main ; if (i) is biggest or equals to 10, lets finish loop
mov ecx, DWORD PTR _i$[ebp] ; loop body: call printing_function(i)
push ecx
call _printing_function
add esp, 4
jmp SHORT $LN2@main ; jump to loop begin
$LN1@main: ; loop end
xor eax, eax
mov esp, ebp

Free download pdf