FOR statement

Language reference ›› Statements ››
Parent Previous Next

for-statement = FOR variable ":=" expression ( TO | DOWNTO ) expression2 { BY constant-expression } DO block .

The BY clause is implemented in some other Pascal-like languages such as MODULA or OBERON, it permits to specify the increment value for <variable>. If present, the BY value must be a constant and evaluated as positive for a TO loop and negative for a DOWNTO loop.

The BY clause is implemented in PMP as an "extended syntax". If the “Extended syntax” project's option is not active it will produce a compilation error.


If <Expression2> does not evaluate to a constant, in the current implementation of PMP the FOR – TO loop is implemented as an equivalent of:



<variable> := <Expression1>;
<Temp> := <Expression2>;
IF <variable> <= <Temp> THEN
 WHILE TRUE DO
   BEGIN
     <Block>
     IF <variable> < <Temp> THEN
       INC(<variable>)
     ELSE
       BREAK;
   END;


And as well the FOR – DOWNTO loop:



<variable> := <Expression1>;
<Temp> := <Expression2>;
IF <variable> >= <Temp> THEN
 WHILE TRUE DO
   BEGIN
     <Block>
     IF <variable> > <Temp> THEN
       DEC(<variable>)
     ELSE
       BREAK;
   END;


If <Expression2> evaluates to a constant, in the current implementation of PMP, the FOR – TO loop is implemented as an equivalent of:



<variable> := <Expression1>;
IF <variable> <= <Expression2> THEN
 WHILE TRUE DO
   BEGIN
     <Block>
     IF <variable> <> <Expression2> THEN
       INC(<variable>)
     ELSE
       BREAK;
   END;


And as well the FOR – DOWNTO loop:



<variable> := <Expression1>;
IF <variable> >= <Expression2> THEN
 WHILE TRUE DO
   BEGIN
     <Block>
     IF <variable> <> <Expression2> THEN
       DEC(<variable>)
     ELSE
       BREAK;
   END;


There are some special behaviors from other “standard” Pascal implementations:


Optimizations:


If <Expression1> and <Expression2> evaluates to the same constant value, the <block> is executed once, no loop code is generated.

If <Expression1> and <Expression2> evaluates to constant values and <Expression1> is over <Expression2>, no code is generated, even for the loop variable assignment.


The loop flow may also be controlled via BREAK and CONTINUE statements.


See also: BREAK, CONTINUE, FOR iterator.