Page 298 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 298

9.4 Loop Statements, Arrays, and Structs                            275



            In Figure 9.10 a for loop has an initialization expression, shown first in the for
        list of expressions; a test expression, shown in the middle; and a loop termination
        expression, shown last:

              * 3:       for(j = k = 0; j != i; j++) k += j;
                     CLRB           ; j in D
                     CLRA
                     TFR    D, X    ; k in X
                     BRA    LI      ; do the test before the loop is done once
              LO :   LEAX D, X      ; this is the statement that is executed in the loop
                     ADDD #1        ; this is the expression done after each loop is done
              LI:    CPD    $0800 ; this is the loop test
                     BNE    LO
        A while loop has a test expression that is executed before the loop is executed once:
              * 4:      while(j != 0) k += —j;
                     BRA    L3      ; do the test first
              L2 :   SUED #1        ; these are the two statements
                     LEAX D, X      ; that are executed in the loop
              L3 :   TBNE   D,L2 ; this is the loop test
        A do while loop has a test expression that is executed after the loop is executed:
              * 5:       do k += j—; while (j != i);
              L4 :   LEAX   D, X    ; these are the two statements
                     DEX            ; that are executed in the loop
                     CPD    $0800 ; this is the loop test
                     BNE    L4

            Figure 9.11 illustrates nested for loops and the two-dimesional array index
        addressing mechanism. This example shows how loop statements can themselves be
        loops, in a nested loop construction, and how optimizing compilers make loops more
        efficient. The outer for loop, for (i = sum =0 ; i < 10; i++) is encoded as an
        initialization:

               CLRA            ; generate 0
               CLRB            ; in high and low bytes
               STD $08 IE      ; store to clear sum
               STAB 1, SP      ; store to clear i

        and by the outer loop termination:
               INC 1, SP        ; count up
               LDAA 1, SP      ; get the variable to be tested
               CMP A #10       ; compare against 10
               BCS    *-40     ; loop as long as i is less than 10
               CMPA #3         ; check if another iteration is to be done
               BCS    *-30     ; if so, branch to the instruction following the initialization
   293   294   295   296   297   298   299   300   301   302   303