Syntax:
for indexVar = firstValue to lastValue [STEP stepValue]
[statementBlock]
next [indexVar]
Description:
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:
- The value of
firstValue is assigned to indexVar (indexVar must be a simple numeric variable).
- 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).
- The value of
indexVar + stepValue is assigned to indexVar. (If you omit the STEP stepValue clause, then incremental value defaults to 1.)
- 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
:
next
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
:
next
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"
next
override _forLoopsAlwaysExecuteAtLeastOnce = _true
for j = 1 to 0
print "Get here" // legacy FutureBasic behavior
next
override _forLoopsAlwaysExecuteAtLeastOnce = _false
for j = 1 to 0
print "Never get here"
next
Example:
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
long if strArray$(p) = searchString$
found = _zTrue
theIndex = p
exit for 'force early exit from loop
end if
next
Note:
The while and do statements provide other useful kinds of loop structures.
See Also:
while; do; exit for