For statement

Description

For statements perform an action in a counting loop (i.e. perform the action for a specified number of times and counts each performance of the action). For statements contain the following:

Usually execution of a for statement is as follows:

  1. The initial value is stored in the control variable.
  2. The statement contained in the for statement is executed.
  3. If the value stored in the control variable is equal to the final value then execution of the for statement is terminated.
  4. The value stored in the control variable is incremented by one (in loops counting upwards), or decremented by one (in loops counting downwards).
  5. Execution of the for statement continues with step 2.
However the following situations can affect the execution of a for statement.

You should not depend on the control variable having any particular value after the execution of a for statement is terminated, unless program execution was transfered out of the for statement by a goto statement.

Normally when executing a for statement it is best if the value of the control variable is changed only by the for statement. If another statement alters the value of a for statement's control variable it usually causes problems in the program. In an apparent effort to protect programmers from making that kind of mistake Standard Pascal (ISO/IEC 7185) defines a number of rules that restrict how control variables are used, and Irie Pascal implements these rules.

The first rule is that control variables must be declared at the same level as the for statement containing them (i.e. if the for statement is in a function or procedure then the control variable must be local to that function or procedure, and if the for statement is in the main program block then the control variable must be global). Keeping the control variable local makes it easier to control access.

The second rule is that neither the for statement nor any function or procedure local to the block containing the for statement shall contain a statement that threatens the control variable. A statement threatens the control variable if the execution of the statement could possibly alter the value stored in the control variable.

Example

The following program uses a for statement to count from 1 to 10.

program CountToTen(output);

   procedure CountToTen;
   var
      i : 1..10;
   begin (* CountToTen *)
      for i := 1 to 10 do
         writeln(i);
   end; (* CountToTen *)

begin
   CountToTen;
end.

Syntax

(NOTE: for clarity some parts of the syntax are omitted, see Irie Pascal Grammar for the full syntax):

   for-statement = 'for' control-variable ':=' initial-value ( 'to' | 'downto' ) final-value
              'do' statement

   control-variable = entire-variable

   initial-value = ordinal-expression

   final-value = ordinal-expression