Skip to content

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, iterator will automatically be declared with type datatype.
  • 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:

vb
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 i

Example 2: Showing that endvalue and stepvalue are cached

vb
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
Print

Example 3: Infinite loop danger with UByte

vb
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 ub

Dialect Differences

  • In -lang fb and -lang deprecated, variables declared inside a For..Next block are visible only inside the block.
  • In -lang qb and -lang fblite, variables have procedure-wide scope.

Differences from QB

  • ByRef arguments cannot be used as counters.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft