Continue

From Free Pascal wiki
Revision as of 20:46, 15 July 2021 by Kai Burghardt (talk | contribs) (→‎application: more)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Deutsch (de) English (en)

The continue (pseudo) routine effectively skips the remainder of the loop body for one iteration, thus jumping back (or forward) to the loop head. It is a non-standardized extension.

Continue, with its special meaning of terminating one iteration, can only be written within loops. It is not a reserved word, therefore you could use it as an identifier, but still access the special routine by writing its fully qualified identifier system.continue. In {$mode MacPas} the cycle statement is an alias for continue.

application

The use of continue is usually disfavored since it “delegitimizes” the loop’s condition expression. If the number of iterations can be predicted before the loop starts, it is even considered bad style to use continue. Instead it is highly recommended to improve the algorithm. Nevertheless, in the case of unpredictable data, and thus an unpredictable number of (complete) iterations, continue is generally acceptable.

program continueDemo(input, output, stdErr);
var
  i, sum: integer;
begin
  sum := 0;
  writeLn('Enter some positive numbers, line by line:');
  
  //       ┌─────────────────────────────────┐
  //       ↓ next iteration: check condition │
  while not eof do                        // │
    begin                                 // │
      readLn(i);                          // │
                                          // │
      if i < 1 then                       // │
        begin                             // │
          writeLn('Hey! Stay positive!'); // │
          continue; // → ────────────────────┘
        end;
      
      {$push}
      {$rangeChecks off}
      sum := sum + i;
      {$pop}
      if sum < 0 then
        begin
          writeLn('I can’t handle that much positivity.');
          halt(1);
        end;
    end;
  
  writeLn('The sum of all your positive numbers is ', sum, '.');
  writeLn('I like that positivity.');
end.

After and at continue (or cycle in {$mode MacPas}) the program jumps back, or in the case of repeat  until forward, to the loop’s condition. The respective condition must be satisfied again before another iteration occurs.

The use of continue can in practice always be avoided by proper if statements. It does not increase the power of Pascal. The above demonstration example would be usually written without a continue. However, if there would be many or several nested if statements, continue is preferred to retain some degree of readability.

see also