9.2.4 The For..to/downto..do statement

Free Pascal supports the For loop construction. A for loop is used in case one wants to calculated something a xed number of times. The prototype syntax is as follows:

_________________________________________________________________________________________________________ For statement
-- --for statement -for-control variable := - initial value----to-----
- ----        -   -        ------------------------downto-----------
        nal value do  statement

-- --            -              -----------------------------------
     control variable variable identi er

-- --         -         -------------------------------------------
     initial value expression

   --        -         --------------------------------------------
--     nal value expression                                            -
___________________________________________________________________

Statement can be a compound statement. When this statement is encountered, the control variable is initialized with the initial value, and is compared with the nal value. What happens next depends on whether to or downto is used:

  1. In the case To is used, if the initial value is larger than the nal value then Statement will never be executed.
  2. In the case DownTo is used, if the initial value is less than the nal value then Statement will never be executed.

After this check, the statement after Do is executed. After the execution of the statement, the control variable is increased or decreased with 1, depending on whether To or Downto is used. The control variable must be an ordinal type, no other types can be used as counters in a loop.

Remark: Contrary to ANSI pascal specications, Free Pascal rst initializes the counter variable, and only then calculates the upper bound.

The following are valid loops:

For Day := Monday to Friday do Work;  
For I := 100 downto 1 do  
  WriteLn ('Counting down : ',i);  
For I := 1 to 7*dwarfs do KissDwarf(i);

If the statement is a compound statement, then the Break (??) and Continue (??) reserved words can be used to jump to the end or just after the end of the For statement.