Hardware Reference
In-Depth Information
automatically be saved in such a way as to avoid destroying previous return ad-
dresses. Recursion works just fine under these conditions. We saw this form of
saving the return address in IJVM in Fig. 4-12.
5.5.6 Loop Control
The need to execute a group of instructions a fixed number of times occurs fre-
quently and thus some machines have instructions to facilitate doing this. All the
schemes involve a counter that is increased or decreased by some constant once
each time through the loop. The counter is also tested once each time through the
loop. If a certain condition holds, the loop is terminated.
One method initializes a counter outside the loop and then immediately begins
executing the loop code. The last instruction of the loop updates the counter and,
if the termination condition has not yet been satisfied, branches back to the first in-
struction of the loop. Otherwise, the loop is finished and it falls through, executing
the first instruction beyond the loop. This form of looping is characterized as test-
at-the-end (or post-test) type looping, and is illustrated in C in Fig. 5-29(a). (We
could not use Java here because it does not have a goto statement.)
i=1;
i=1;
L1:
if (i > n) goto L2;
L1:
first-statement;
first-statement;
.
.
.
.
.
.
last-statement;
last-statement
i=i+1;
i=i+1;
if (i < n) goto L1;
goto L1;
L2:
(a)
(b)
Figure 5-29. (a) Test-at-the-end loop. (b) Test-at-the-beginning loop.
Test-at-the-end looping has the property that the loop will always be executed
at least once, even if n is less than or equal to 0. Consider, as an example, a pro-
gram that maintains personnel records for a company. At a certain point in the pro-
gram, it is reading information about a particular employee. It reads in n , the num-
ber of children the employee has, and executes a loop n times, once per child, read-
ing the child's name, sex, and birthday, so that the company can send him or her a
birthday present, one of the company's fringe benefits. If the employee does not
have any children, n will be 0 but the loop will still be executed once sending pres-
ents and giving erroneous results.
Figure 5-29(b) shows another way of performing the test (pretest) that works
properly even for n less than or equal to 0. Notice that the testing is different in the
two cases, so that if a single ISA instruction does both the increment and the test,
the designers are forced to choose one method or the other.
 
 
Search WWH ::




Custom Search