Next: , Previous: Simple Loops, Up: Control Structures


5.8.3 Counted Loops

The basic counted loop is:

     limit start
     ?DO
       body
     LOOP

This performs one iteration for every integer, starting from start and up to, but excluding limit. The counter, or index, can be accessed with i. For example, the loop:

     10 0 ?DO
       i .
     LOOP

prints 0 1 2 3 4 5 6 7 8 9

The index of the innermost loop can be accessed with i, the index of the next loop with j, and the index of the third loop with k.

i       R:n – R:n n        core       “i”

j       R:w R:w1 R:w2 – w R:w R:w1 R:w2        core       “j”

k       R:w R:w1 R:w2 R:w3 R:w4 – w R:w R:w1 R:w2 R:w3 R:w4        gforth       “k”

The loop control data are kept on the return stack, so there are some restrictions on mixing return stack accesses and counted loop words. In particuler, if you put values on the return stack outside the loop, you cannot read them inside the loop1. If you put values on the return stack within a loop, you have to remove them before the end of the loop and before accessing the index of the loop.

There are several variations on the counted loop:

Unfortunately, +DO, U+DO, -DO, U-DO and -LOOP are not defined in ANS Forth. However, an implementation for these words that uses only standard words is provided in compat/loops.fs.

Another counted loop is:

     n
     FOR
       body
     NEXT

This is the preferred loop of native code compiler writers who are too lazy to optimize ?DO loops properly. This loop structure is not defined in ANS Forth. In Gforth, this loop iterates n+1 times; i produces values starting with n and ending with 0. Other Forth systems may behave differently, even if they support FOR loops. To avoid problems, don't use FOR loops.


Fußnoten

[1] well, not in a way that is portable.