www.delorie.com/gnu/docs/gforth/gforth_91.html   search  
Buy GNU books!

Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.8.3 Counted Loops

The basic counted loop is:
limit start

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 .
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.

doc-i doc-j doc-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 loop(12). 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:
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.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003