For-Next

From REALbasicWiki

Jump to: navigation, search

For-Next is a looping control structure.


[edit] Syntax

For variableName [as Numeric Datatype] = firstIndex to | downto lastIndex [Step value]
  //
Next [variableName]

[edit] Discussion

A For-Next block is a looping control structure containing an explicit counter. This counter must be a variable, and must satisfy the same conditions as a variable passed by reference. The scope of the counter can be limited to the block adding the optional as numeric datatype.

The counter variable is initialized to firstIndex at the start of the first iteration; firstIndex can be a constant, expression, or function. At the beginning of each subsequent iteration, the counter variable is incremented, if the keyword to is present, or decremented, if the keyword downto is present, by 1, by default. If the optional Step value clause is present, the counter is changed by value, which can be a constant, expression, or function.

The loop exits when the counter variable is greater than ( if the keyword to is present) or less than (if the keyword downto is present) lastIndex. lastIndex may be a constant, expression, or function. Note that the value of lastIndex is evaluated each iteration.


The value of the counter variable can be modified in the body of the loop. But this subverts the semantic purpose of a For-Next loop; if you need to do such a thing, you should instead consider using a While-Wend or Do-Loop structure.



[edit] Invalid Syntax Examples

You cannot use an expression as the counter.

dim i as Integer
for 2*i = 1 to 10
next

The counter must be a dot-free variable.

for App.counter = 1 to 10
next


The variable i is declared twice, because the i as Integer is also a variable declaration.

dim i as Integer

for i as Integer = 1 to 10
...
next


The scope of the variable i is limited to the block, so this example will not compile:

for i as Integer = 1 to 10
...
next
dim index as Integer = i


The Next variable (j) does not match the loop's counter variable (i).

for i as Integer = 1 to 47
...
next j
Personal tools
related