FutureBasic Logo

<<    Index    >> FutureBasic

for   statement

for indexVar = firstValue to lastValue [step stepValue]
   [statement block]
next [indexVar]

for objectVar in collectionVar [step -1]
   [statement block]

Description - Syntax (1)

The for statement marks the beginning of a "for-loop," which must end with a next statement. A for-loop is useful when you want to repeat the execution of a block of statements for a particular number of times. This is what happens when a for-loop is encountered:
  1. The value of firstValue is assigned to indexVar (indexVar must be a simple numeric variable).
  2. The statements in statementBlock are executed. statementBlock can contain any number of statements, possibly including other for-loops (but note that any for-loop that's "nested" within statementBlock should not use the same indexVar as the "outer" for-loop).
  3. The value of indexVar + stepValue is assigned to indexVar. (If you omit the step stepValue clause, then incremental value defaults to 1.)
  4. The new value of indexVar is compared with lastValue, to see whether the loop should be repeated:
      If stepValue is positive, then repeat the loop (go to Step 2) if indexVar<=lastValue.
      If stepValue is negative, then repeat the loop (go to Step 2) if indexVar>=lastValue.

For example, consider this loop:

for n = 3 to sqr(x) step 2

In the above, the sqr function is called after each iteration of the loop. Assuming that the value of x doesn't change within the loop, we are needlessly recalculating the same sqr value at each iteration. It would be much faster to do it this way:

sqrx = sqr(x)
for n = 3 to sqrx step 2

Here the sqr function is called only once.

Implementation changes:
A design mistake in FutureBasic version 4 and earlier, apparently inherited from Applesoft BASIC, has been corrected that made for/next loops always execute at least once. Compatibility with legacy FutureBasic code can be obtained by overriding a special predefined constant as shown below.

dim as long j
 for j = 1 to 0
 print "never get here"

override _forLoopsAlwaysExecuteAtLeastOnce = _true

 for j = 1 to 0
 print "get here" // legacy FutureBasic behavior

override _forLoopsAlwaysExecuteAtLeastOnce = _false

 for j = 1 to 0
 print "never get here"

Sometimes it's useful to exit a for-loop "early," after some condition within statementBlock has been met. The standard way to do this is to use exit for.
for p = 1 to maxStrings
  if strArray(p) = searchPascalString
    found = _zTrue
    theIndex = p
    exit for 'force early exit from loop
  end if

Description Syntax (2)

This syntax option provides simplified access to Core Foundation (CF) and NS collection objects such as arrays and dictionaries.

dim as CFArrayRef array
dim as CFStringRef string

array = @[@"One", @"Two", @"Three", @"Four", @"Five"]
for string in array

The while and do statements provide other useful kinds of loop structures.

See also
while; do; exit for; break; continue