For
│
Deutsch (de) │
English (en) │
français (fr) │
русский (ru) │
for
is a keyword used in conjunction with other keywords to create loops.
loop with iterator variable
for
used along with to
/downto
and do
constructs a loop in which the value of a control variable is incremented or decremented by 1
passing every iteration.
behavior
for controlVariable := start to finalValue do
begin
statement;
end;
In this example controlVariable
is first initialized with the value of start
(but cmp. § “legacy” below).
If and as long as controlVariable
is not greater than finalValue
, the begin
… end
frame with all its statements is executed.
By reaching end
controlVariable
is incremented by 1
and the comparison is made, whether another iteration, whether the statement-frame is executed again.
reverse direction
By exchanging to
with downto
, the variable – in the example controlVariable
– is decremented by 1
and the condition becomes “as long as the control variable is not less than the final value.”
constraints
scope requirements
The control variable has to be local inside nested routines.
A routine is nested, if routine variables tagged with the modifier is nested
can store its address.
Nevertheless, a global variable is always allowed as a control variable.
immutable requirement
While inside in a loop, it is imperative not to mess with the loop variable.
Plain assignments – e. g. controlVariable := 2
– are caught by the compiler reporting “Illegal assignment to for-loop variable "controlVariable"”.
However, indirect manipulations are not prevented:
program iteratorManipulation(input, output, stderr);
var
i: longint;
procedure foo;
begin
i := 1;
end;
begin
for i := 0 to 2 do
begin
writeLn(i);
foo;
end;
end.
The global variable i
is modified by calling foo
.
The program runs an infinite loop.
type restrictions
The type of controlVariable
has to be enumerable.
Assuming your system operates on ASCII you can do
var
c: char;
begin
for c := 'a' to 'z' do
begin
writeLn(c);
end;
end.
or generally use any type that is enumerable.
other step widths
Other step widths than 1
or -1
are not possible by utilizing this syntax.
You have to use other loop constructs such as while
… do
and manually initialize, compare and change the controlVariable
.
The matter, whether FreePascal could provide a syntax specifying other step widths, came up several times. In general it was regarded as “syntactic sugar”, though, and in order to stay compatible Pascal’s core, or Delphi’s extensions, in order to avoid any impetuous decisions, the developers remained rather conservative and rejected any changes in that direction.
See also FPC issue 25549.
limits
Note, as it is common in mathematics when writing sums [math]\displaystyle{ \sum_{n=0}^{k} }[/math] or products [math]\displaystyle{ \prod_{n=1}^{k} }[/math] the limits are inclusive.
for i := 5 to 5 do
begin
writeLn(i);
end;
This excerpt will print one line with 5
, though you might be fooled by such thoughts as “5 to 5 – the difference is zero. So the body must never be executed.”
This is in fact wrong.
Not the difference determines the number of iterations, but the cardinality of the set constructed by the expression [start..finalValue]
.
This can be an empty set, or in the case of [5..5]
just the single-element set [math]\displaystyle{ \left\{5\right\} }[/math].
Loop Completion
Note that the value of the "for loop variable" is undefined after a loop has completed or if a loop is not executed at all. However, if the loop was terminated prematurely with an exception or a break (or even a goto statement), the loop variable retains the value it had when the loop was exited.
In case of empty loops (where the body is never executed), even the start
value is not loaded.
Rationale:
The controlVariable
exists for usage inside the loop’s body.
If the loop’s body is not entered, then the value might remain unused.
We generally avoid unused values, i. e. any unnecessary assignment without successive reads.
short syntax
For single statements writing a surrounding begin
… end
frame can be skipped resulting in:
for controlVariable := start to final do
statement;
It is advised though, to make use of that only in justified cases, where the readability is improved and it is very unlikely the loop is expanded by any additional statement.
Too many programmers inadvertently fell for the pitfall before and added a properly indented line forgetting it requires a surrounding begin
… end
then, too.
Make it a habit and always accompany for
-loops with begin
… end
, leaving the option to possibly eliminate those at a later stage, prior a complete code freeze (but not right in the middle of development).
loop with elements
With for
… in
loops the variable that is changed every iteration represents an element out of a collection.
This works on strings, arrays, sets, and any other custom collection that implements the required iterators. Looping over an empty collection simply does nothing.
type
furniture = (chair, desk, bed, wardrobe);
arrangement = set of furniture;
var
thing: furniture;
begin
writeLn('all available pieces of furniture:');
for thing in arrangement do
begin
writeLn(thing);
end;
end.
In contrast to other loops, an index variable is not provided.
In the above example ord(thing)
will return an index, but it has to be additionally retrieved while it inherently exists yet still inaccessible.
Proposals were made, whether and how to extend the syntax allowing to specify an index variable that is adjusted with every iteration.
special commands
Inside loops (including for
-loops) two special commands tamper with the regular loop-program-flow.
system.continue
skips the rest of the statements in one iteration.
Effectively in a for
-loop the next element/index is immediately assigned to the control variable, the regular check is performed, and processing of all the statements might start from the top again.
Additionally system.break
instantly skips the whole loop altogether.
This is different to system.exit
, which exits the whole frame, but loops do not create frames (but blocks do).
Their usage however is usually discredited, since they “disqualify” the loop’s iteration condition. One has to know a loop’s body contains such commands, in order to actually determine how often a loop is executed. Without such, you can tell how many times a loop is run just by inspecting the loop’s head or tail respectively.
see also
Keywords: begin — do — else — end — for — if — repeat — then — until — while