Name

For Keyword

Syntax

for Variable := Expr1 to Expr2 do Statement
for Variable := Expr1 downto Expr2 do Statement

Description

The for keyword introduces a for loop. A for loop evaluates the expressions that specify the limits of the loop, then performs the loop body repeatedly, assigning a new value to the loop control variable before each loop iteration. The loop control variable must be a local variable.

The types of Variable, Expr1, and Expr2 must match and must be ordinal types: integer, character, or enumerated. Integer values outside the range of the Integer type are not supported. Instead, Delphi silently maps the Expr1 and Expr2 expressions into the range of Integer, giving results you might not expect.

Tips and Tricks

  • Delphi optimizes the loop by computing the number of iterations before starting the loop. Changing the limits of the loop (Expr1 and Expr2) inside the loop does not affect the number of times the loop executes.

  • Because the for loop works only with values that fit in an Integer, if you want to iterate over Cardinal or Int64 values, you must use a while loop.

  • After the loop terminates normally, the value of the loop control variable is not defined. If the loop exits because of a Break or goto statement, the loop control variable retains its last value.

See Also

Do Keyword, Integer Type, Repeat Keyword, While Keyword

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.