Monday, August 2, 2010

Loops

A loop is accomplished by using a JMP instruction. If the loop is to execute again, then you JMP back to the top of the loop body. If you are looping a certain number of times, it is usually easier to count down instead of count up, because it doesn't take an extra register to hold your final state. Here are examples of two different kinds of loops:

Pascal:

FOR i := 10 DOWNTO 1 DO
BEGIN
... (* loop1 body *)
END;
WHILE (x <> 20) DO
BEGIN
... (* loop2 body *)
END;
C++:

for (i=10; i > 0; i--) {
... // loop1 body
}
while (x != 20) {
... // loop2 body
}
Assembly:

SET r1, 10 ; r1 will take the place of i
SET r2, 1 ; r2 will hold the value to subtract each time
LOOP1TOP:
... ; loop1 body
SUB r1, r1, r2 ; subtract one from r1
CMP r1, r0
JMP NEQ, LOOP1TOP ; keep going until r1 gets to zero

SET r2, 20 ; r2 will hold our end condition
LOOP2TOP:
LOAD r1, X ; load the x variable
CMP r1, r2
JMP EQ, LOOP2END ; if we're done, skip to end of loop
... ; loop2 body
LOOP2END:

Usually in Assembly, we always use this kind of loops because it is helpful for the conditional statement.

No comments:

Post a Comment