A For
loop statement loops based on a set of bounds. A For
loop specifies a lower bound, an upper bound and an optional step value. The variable of a For
statement must be of a type that supports the greater than operator, the less than operator and the addition operator, otherwise there is an error.
At the beginning of the loop, the three expressions are evaluated in order: the lower bound, the upper bound and the step value. If the step value is omitted, it is implicitly the literal 1
. All three expressions must be implicitly convertible to the type of the variable. If the For
loop variable is of type Object
, then at runtime at least one of the expressions must be of a numeric type and all three expressions must be coercible to the widest numeric type amongst them.
The lower bound expression is assigned to the variable and the variable is then compared to see if it is greater than the upper bound if the step expression is positive, or less than the upper bound is the step expression is negative. If it is, the For
loop terminates, otherwise the loop block executes. At the Next
statement, the step value is added to the variable and execution returns to the top of the loop. If a variable is specified after the Next
keyword, it must be the same as the one used after the For
keyword.
If the loop control variable is a property, the property must have both a property getter and a property setter, otherwise there is an error. If the loop control variable is a ReadOnly
data member, the loop must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.
For
VariableExpression =
Expression To
Expression [ Step
Expression ] StatementTerminator Next
[ VariableExpression ] StatementTerminator