FOR...NEXT
Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFornext Last revised: 2021-09-28
Control flow statement for looping.
Syntax
For iterator [As datatype] = startvalue To endvalue [Step stepvalue]
[statement block]
Next [iterator]Parameters
- iterator — A variable identifier used to iterate from an initial value to an end value.
- datatype — If specified,
iteratorwill automatically be declared with typedatatype. - startvalue — An expression denoting the starting value of the iterator.
- endvalue — An expression used to compare with the value of the iterator.
- stepvalue — An expression added to the iterator after every iteration.
Description
A For...Next loop initializes iterator to startvalue, then executes the statement block, incrementing iterator by stepvalue until it exceeds endvalue. If stepvalue is not given, it defaults to 1.
The values of stepvalue and endvalue are stored internally immediately following execution of the For statement and cannot be changed inside the loop.
The iterator must be an intrinsic scalar: only Static/Shared variables and local variables can be used.
The iterator may be defined in the For scope using As datatype syntax — it is created and destroyed within the For...Next scope.
If endvalue is less than startvalue, a negative stepvalue must be specified or the statement block will not execute.
Exit For: Terminates the loop, execution resumes after the Next statement.
Continue For: Skips the rest of the statement block, increments the counter, and restarts the loop.
Note: For integer data types, it is not possible to loop up to the highest possible value of the type, because the loop breaks when the incremented variable exceeds endvalue.
For, Next, and Step are operators that can be overloaded in user-defined types.
Examples
Example 1:
Print "counting from 3 to 0, with a step of -0.5"
For i As Single = 3 To 0 Step -0.5
Print "i is " & i
Next iExample 2: Showing that endvalue and stepvalue are cached
Dim As Integer i, j, k
j = 9: k = 1
For i = 0 To j Step k
j = 0: k = 0 '' Changing j and k has no effect on the current loop.
Print i;
Next i
PrintExample 3: Infinite loop danger with UByte
For ub As UByte = 240 To 255 '' Infinite loop: 255+1=256 can never be reached by UByte
Print ub
If Inkey <> "" Then Exit For
Sleep 10
Next ubDialect Differences
- In
-lang fband-lang deprecated, variables declared inside aFor..Nextblock are visible only inside the block. - In
-lang qband-lang fblite, variables have procedure-wide scope.
Differences from QB
ByRefarguments cannot be used as counters.