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.




Programming from the Ground Up
Programming from the Ground Up
ISBN: 0975283847
EAN: 2147483647
Year: 2006
Pages: 137

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net