Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Next: 5.3.3 Conditionals Up: 5.3 Assembly Language Examples Previous: 5.3.

1 Variables

5.3.2 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:

James Clingenpeel Thu Feb 29 18:00:38 MST 1996

Next: 6 Traps Up: 5.3 Assembly Language Examples Previous: 5.3.2 Loops

5.3.3 Conditionals
``If'' statements are also done by using JMP instructions. Multiple conditions can be tested by using several JMP instructions. Here are some examples of how to do ``if'' statements: Pascal:
IF (x = 10) THEN BEGIN ... (* then part 1 *) END ELSE BEGIN ... (* else part 1 *) END; IF ((x<>10) AND (y>20)) THEN BEGIN ... (* then part 2 *) END;

C++:
if (x == 10) { ... // then part 1 } else { ... // else part 1 } if ((x!=10) && (y>20)) { ... // then part 2 }

Assembly:
LOAD r1, X SET r2, 10 CMP r1, r2 JMP NEQ, ELSE1 then part ; load the variable x into r1 ; set r2 to immediate value 10 ; if r1 <> r2, then jump to the else part, otherwise do the

... JUMP END1 ELSE1: ... END1:

; then part 1 ; jump over the else part ; else part 1 load the variable x into r1 set r2 to immediate value 10 if x <> 10 go on to next test otherwise skip past then part 2 load the variable y into r1 set r2 to immediate value 20 if y > 20 go on to then part 2 otherwise skip past part 2

LOAD r1, X ; SET r2, 10 ; CMP r1, r2 JMP NEQ, TEST2 ; JUMP END2 ; TEST2: LOAD r1, Y ; SET r2, 20 ; CMP r1, r2 JMP GT, THEN2 ; JUMP END2 ; THEN2: ... ; then END2:

James Clingenpeel Thu Feb 29 18:00:38 MST 1996

You might also like