Sign in Join
Wiki copytemporary

For: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
1-` for` is a [[Keyword|keyword]] used in conjunction with other keywords to create [[Loops|loops]].
1+`for` is a [[Keyword|keyword]] used in conjunction with other keywords to create [[Loops|loops]].
22
33## loop with iterator variable
44
55`for` used along with `to`/`downto` and [[Do|`do`]] constructs a loop in which the value of a control variable is incremented or decremented by `1` passing every iteration.
66
77### behavior
88```
99for controlVariable := start to finalValue do
1010 begin
1111 statement;
1212 end;
1313```
1414
1515In 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|`begin`]] … [[End|`end`]] [[Frame|frame]] with all its [[statement|statements]] is executed. By reaching `end` `controlVariable` is [[Inc|incremented]] by `1` and the comparison is made, whether another iteration, whether the statement-frame is executed again.
1616
1717### reverse direction
1818
1919By exchanging `to` with `downto`, the variable – in the example `controlVariable` – is [[Dec|decremented]] by `1` and the condition becomes “as long as the control variable is not less than the final value.”
2020
2121### constraints
2222
2323#### scope requirements
2424
25-The control variable has to be [[Local variables|local]] inside nested [[Routine|routines]]. A routine is nested, if [routine variables](</index.php?title=Procedural_variable&action=edit&redlink=1> "Procedural variable \(page does not exist\)") tagged with the modifier `is nested` can store its address. Nevertheless, a [[Global variables|global variable]] is always allowed as a control variable.
25+The control variable has to be [[Local variables|local]] inside nested [[Routine|routines]]. A routine is nested, if [[Procedural variable|routine variables]] tagged with the modifier `is nested` can store its address. Nevertheless, a [[Global variables|global variable]] is always allowed as a control variable.
2626
2727#### immutable requirement
2828
2929While 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:
3030```
3131program iteratorManipulation(input, output, stderr);
3232
3333 var
3434 i: longint;
3535
3636 procedure foo;
3737 begin
3838 i := 1;
3939 end;
4040
4141 begin
4242 for i := 0 to 2 do
4343 begin
4444 writeLn(i);
4545 foo;
4646 end;
4747 end.
4848```
4949
5050The global variable `i` is modified by calling `foo`. The program runs an [[Infinite loop|infinite loop]].
5151
5252#### type restrictions
5353
5454The [[Data type|type]] of `controlVariable` has to be enumerable. Assuming your system operates on [[ASCII]] you can do
5555```
5656var
5757 c: char;
5858 begin
5959 for c := 'a' to 'z' do
6060 begin
6161 writeLn(c);
6262 end;
6363 end.
6464```
6565
6666or generally use any type that is enumerable.
6767
6868#### other step widths
6969
7070Other step widths than `1` or `-1` are not possible by utilizing this syntax. You have to use other loop constructs such as [[While|`while`]] … `do` and manually initialize, compare and change the `controlVariable`.
7171
7272The matter, whether [[FPC|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.
7373
7474See also [FPC issue 25549](<https://gitlab.com/freepascal.org/fpc/source/-/issues/25549>).
7575
7676### limits
7777
7878Note, 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_.
7979```
8080for i := 5 to 5 do
8181 begin
8282 writeLn(i);
8383 end;
8484```
8585
8686This 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].
8787
8888### Loop Completion
8989
9090Note 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.
9191
9292In 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.
9393
9494### short syntax
9595
9696For _single_ statements writing a surrounding `begin` … `end` frame can be skipped resulting in:
9797```
9898for controlVariable := start to final do
9999 statement;
100100```
101101
102102It 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.
103103
104104Make 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).
105105
106106## loop with elements
107107
108108With [[for-in loop|`for` … `in` loops]] the variable that is changed every iteration represents an element out of a collection. This works on strings, [[Array|arrays]], [[Set|sets]], and any other custom collection that implements the required iterators. Looping over an empty collection simply does nothing.
109109```
110110type
111111 furniture = (chair, desk, bed, wardrobe);
112112 arrangement = set of furniture;
113113 var
114114 thing: furniture;
115115 begin
116116 writeLn('all available pieces of furniture:');
117117 for thing in arrangement do
118118 begin
119119 writeLn(thing);
120120 end;
121121 end.
122122```
123123
124124In 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. [[for-in loop|Proposals]] were made, whether and how to extend the syntax allowing to specify an index variable that is adjusted with every iteration.
125125
126126## special commands
127127
128128Inside loops (including `for`-loops) two special commands tamper with the regular loop-program-flow. [`system.continue`](<https://www.freepascal.org/docs-html/rtl/system/continue.html>) 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 [[Break|`system.break`]] instantly skips the whole loop altogether. This is different to [`system.exit`](<https://www.freepascal.org/docs-html/rtl/system/exit.html>), which exits the whole frame, but loops do not create frames (but [[Block|blocks]] do).
129129
130130Their 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.
131131
132132## see also
133133
134134 * [[Example: Why the loop variable should be of signed type]]
135- * [`{$rangechecks}`](</index.php?title=sRangechecks&action=edit&redlink=1> "sRangechecks \(page does not exist\)")
135+ * [[sRangechecks|`{$rangechecks}`]]
136136
137137
138138**Keywords:** [[Begin|begin]] — [[Do|do]] — [[Else|else]] — [[End|end]] — for — [[If|if]] — [[Repeat|repeat]] — [[Then|then]] — [[Until|until]] — [[While|while]]
139139
140140---
141141*From the Free Pascal wiki, page "For", as the Internet Archive kept it on 2025-03-19, last changed on 2024-08-15. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history