FOR Loops

Navigation:  Appendices > Macro Language > Compiled Code > Compiled Code Samples >

FOR Loops

Previous pageReturn to chapter overviewNext page

As you may have noticed there is no op-code for the for statement. The reason is that there is no need for it. The for loop is really a while loop with the following differences :

 

The branching condition is that the value of a counter variable be in the range from the starting value to the ending value.

The for loop takes care of initializing the counter variable to the starting value, and of increasing the counter's value which each iteration.

 

Consider the following source code.

 

for nCtr = nStart to nEnd step nStep

 // do something

endfor

 

When compiled it generates the following (the letters in the margin are added here for illustration purposes).

 

a) 0008 CALL nCtr=$0BA(@nStart|@nStep)  //Decrease

b) 0008 CALL nCtr=$0AA(@nCtr|@nStep)  //Add

c) 0008 CALL b001=$0AG(@nCtr|@nEnd|@nStep)  //CheckLoopBoundary

d) 0008 IF_001 @b001 jne+0002

 

e) 0010 JMP-0003  //GOFR_001

f) 0010 ENDF_001

 

We see that the code sequence is as follows

 

a                // first time through

bcde        // every other loop

bcde        // …

bcdf        // until CheckLoopBoundary is false and execution jumps to f

 

With a little thought it becomes clear that the while loop can always be used to replace a for loop. That is why their compiled code is so similar. However, at the source code level the use of a for loop, when appropriate makes code much more legible.


Topic 108220 updated on 08-Mar-2002.
Topic URL: http://www.qppstudio.net/webhelp/index.html?forloops.htm