Page 136 - ARM 64 Bit Assembly Language
P. 136

122 Chapter 5


                                              Listing 5.14 for loop in C.
                            .
                1           . .
                2   for (int i = 0; i < 10; i++)
                3   {
                4     printf("Hello World - %d\n", i);
                5   }
                            .
                6           . .



                                 Listing 5.15 for loop re-written as a pre-test loop in C.
                            .
                1           . .
                2   int i = 0;
                3   while (i < 10)
                4   {
                5     printf("Hello World - %d\n", i);
                6     i++;
                7   }
                            .
                8           . .


                  or post-test loop. However, with the addition of an if-then construct, any loop can be imple-
                  mented as a pre-test loop. The following sections show how loops can be converted from one
                  form to another.

                  5.3.3.1 Pre-test conversion

                  Most assembly languages do not have a for loop. However, any for loop can be converted to
                  a pre-test loop. Listing 5.14 shows a simple C program with a for loop. The program prints
                  “Hello World” ten times, appending an integer to the end of each line.
                  In order to write an equivalent program in assembly, the programmer must first re-write the
                  for loop as a pre-test loop. Listing 5.15 shows the program re-written so that it is easier to
                  translate into assembly. Note that the initialization of the loop variable has been moved to
                  its own line before the while statement. Also, the loop variable is modified on the last line
                  of the loop body. This is a straightforward conversion from one type of loop to another type.
                  Listing 5.16 shows a translation of the pre-test loop structure into AArch64 assembly.


                  5.3.3.2 Post-test conversion
                  If the programmer can guarantee that the body of a for loop will always execute at least once,
                  then the for loop can be converted to an equivalent post-test loop. This form of loop is more
   131   132   133   134   135   136   137   138   139   140   141