Webster
Webster

Reputation: 91

Nested Loop in Assembly Language

I am newbie in assembly language and i couldn't handle the nested loop statement. I want the same expression in such as the other languages like:

for(i=0;i<10;i++){
  for(j=0;j<10;j++){
     statements....
  }
}

I want this expression in assembly language. Thanks...

Upvotes: 2

Views: 12354

Answers (2)

Brendan
Brendan

Reputation: 37214

Let's break this down one step at a time. The first step is to break up the for into its separate pieces:

    i=0;
    do {
        j=0;
        do {
            /* statements.... */
            j++;
        } while(j < 10);
        i++;
    } while(i < 10);

The while is mostly just a test and a jump:

    i=0;
second:
    j=0;
first:
    /* statements.... */
    j++;
    if(j < 10)
        goto first;
    i++;
    if(i < 10)
        goto second;

Next, rename the variables so they have the names of registers:

    ebx=0;
second:
    ecx=0;
first:
    /* statements.... */
    ecx++;
    if(ecx < 10)
        goto first;
    ebx++;
    if(ebx < 10)
        goto second;

Now it's so close to assembly it's trivial to convert:

    mov ebx,0          ;ebx=0;
second:
    mov ecx,0          ;ecx=0;
first:
                       ;/* statements.... */
    inc ecx            ;ecx++;
    cmp ecx,10         ;if(ecx < 10)
    jb first           ;goto first;
    inc ebx            ;ebx++;
    cmp ebx,10         ;if(ebx < 10)
    jb second          ;goto second;

Upvotes: 4

Here's a simple example I wrote using inline assembly in C, I've tested it in Visual Studio which uses Intel notation. I'm going to count in eax, which is the register used for function return values, all iterations of the loops (i.e. 100). ebx holds the i counter and ecx holds the j counter.

Be careful when you use these if you use them inline, ecx is used for the this reference inside objects and it's also used by mul and div. You can use whatever register you like or even the stack. I use xor to reset the counters since the xor operation is cheaper than a mov eax,0 operation.

#include <stdio.h>

int countLoops()
{
    _asm
    {
        xor eax,eax
        xor ebx,ebx
        xor ecx,ecx


outer_loop :
        cmp ebx,10
        je final
        add ebx,1

inner_loop:
        cmp ecx,10
        je reset_inner_loop
        add ecx,1

        add eax,1

        jmp inner_loop

reset_inner_loop:
        xor ecx,ecx
        jmp outer_loop

final:

    };
}

int main(void )
{
    int numOfLoops = countLoops();
    printf("%d\n", numOfLoops);
    return 0;
}

This question has also been answered before here.

Upvotes: 1

Related Questions