Team LiB
Previous Section Next Section

Loops

Loops work a lot like if statements in assembly language - the blocks are formed by jumping around. In C, a while loop consists of a loop body, and a test to determine whether or not it is time to exit the loop. A for loop is exactly the same, with optional initialization and counter-increment sections. These can simply be moved around to make a while loop.

In C, a while loop looks like this:

while(a < b)
{
 /* Do stuff here */
}

/* Finished Looping */

This can be rendered in assembly language like this:

loop_begin:
 movl  a, %eax
 movl  b, %ebx
 cmpl  %eax, %ebx
 jge   loop_end

loop_body:
 #Do stuff here

 jmp loop_begin

loop_end:
 #Finished looping

The x86 assembly language has some direct support for looping as well. The %ecx register can be used as a counter that ends with zero. The loop instruction will decrement %ecx and jump to a specified address unless %ecx is zero. For example, if you wanted to execute a statement 100 times, you would do this in C:

 for(i=0; i < 100; i++)
 {
  /* Do process here */
 }

In assembly language it would be written like this:

loop_initialize:
 movl $100, %ecx
loop_begin:
 #
 #Do Process Here
 #

 #Decrement %ecx and loops if not zero
 loop loop_begin

rest_of_program:
 #Continues on to here

One thing to notice is that the loop instruction requires you to be counting backwards to zero. If you need to count forwards or use another ending number, you should use the loop form which does not include the loop instruction.

For really tight loops of character string operations, there is also the rep instruction, but we will leave learning about that as an exercise to the reader.


Team LiB
Previous Section Next Section