FOR / NEXT

Syntax

Syntax: FOR var = start TO end [STEP n] : ... : NEXT [var]
Source: PB_STMT_FOR handler (pb_codegen.c:6560)

Description

Executes a block of code a specific number of times. The loop counter variable starts at start and increments by STEP (default 1) on each iteration until it passes end. The compiler checks the loop condition at the top of each iteration. Supports both positive and negative STEP values. EXIT FOR can prematurely terminate the loop, and ITERATE FOR skips the remainder of the current iteration.

Parameters

ParameterDescription
varA numeric variable (typically LOCAL LONG) used as the loop counter. Its value changes each iteration.
startThe initial value assigned to the counter variable before the first iteration.
endThe final (boundary) value. The loop exits when the counter passes this value.
STEP nOptional increment value. Defaults to 1. Can be negative for counting down. Can be an expression.

Example

FUNCTION PBMAIN() AS LONG
    LOCAL i AS LONG
    
    ' Loop 1 to 10
    FOR i = 1 TO 10
        PRINT "Count: "; i
    NEXT i
    
    ' Loop with STEP 2 (odd numbers)
    FOR i = 1 TO 9 STEP 2
        PRINT "Odd: "; i
    NEXT i
    
    ' Countdown loop
    FOR i = 10 TO 1 STEP -1
        PRINT "Countdown: "; i
    NEXT i
    
    FUNCTION = 0
END FUNCTION

Generated Assembly (Positive STEP)

; Evaluate start -> RAX
mov    [rbp - var_offset], rax        ; FOR var = start

__pb_for_N:                           ; LOOP TOP
; Evaluate end -> RAX
mov    r10, rax                       ; r10 = end value
mov    rax, [rbp - var_offset]        ; reload loop variable
cmp    rax, r10                       ; compare var, end
jg     __pb_for_end_N                 ; exit if var > end

; ... loop body ...
; EXIT FOR jumps here: __pb_for_end_N
; ITERATE FOR jumps here: __pb_for_iter_N

__pb_for_iter_N:                      ; ITERATE label
mov    rax, 1                         ; default step = 1
add    [rbp - var_offset], rax        ; var = var + step
jmp    __pb_for_N                     ; loop back

__pb_for_end_N:                       ; EXIT point

Negative STEP

; Same structure but exit check reverses:
jl     __pb_for_end_N                 ; exit if var < end (negative step)
; ADD still used (negative step value subtracts)

EXIT FOR

jmp    __pb_for_end_N                 ; jump to end label

ITERATE FOR

jmp    __pb_for_iter_N                ; jump to increment + check