For: what changed
Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | - | ||
| 1 | + | `for` is a [[Keyword|keyword]] used in conjunction with other keywords to create [[Loops|loops]]. | |
| 2 | 2 | ||
| 3 | 3 | ## loop with iterator variable | |
| 4 | 4 | ||
| 5 | 5 | `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. | |
| 6 | 6 | ||
| 7 | 7 | ### behavior | |
| 8 | 8 | ``` | |
| 9 | 9 | for controlVariable := start to finalValue do | |
| 10 | 10 | begin | |
| 11 | 11 | statement; | |
| 12 | 12 | end; | |
| 13 | 13 | ``` | |
| 14 | 14 | ||
| 15 | 15 | 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|`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. | |
| 16 | 16 | ||
| 17 | 17 | ### reverse direction | |
| 18 | 18 | ||
| 19 | 19 | By 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.” | |
| 20 | 20 | ||
| 21 | 21 | ### constraints | |
| 22 | 22 | ||
| 23 | 23 | #### scope requirements | |
| 24 | 24 | ||
| 25 | - | ||
| 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. | |
| 26 | 26 | ||
| 27 | 27 | #### immutable requirement | |
| 28 | 28 | ||
| 29 | 29 | 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: | |
| 30 | 30 | ``` | |
| 31 | 31 | program iteratorManipulation(input, output, stderr); | |
| 32 | 32 | ||
| 33 | 33 | var | |
| 34 | 34 | i: longint; | |
| 35 | 35 | ||
| 36 | 36 | procedure foo; | |
| 37 | 37 | begin | |
| 38 | 38 | i := 1; | |
| 39 | 39 | end; | |
| 40 | 40 | ||
| 41 | 41 | begin | |
| 42 | 42 | for i := 0 to 2 do | |
| 43 | 43 | begin | |
| 44 | 44 | writeLn(i); | |
| 45 | 45 | foo; | |
| 46 | 46 | end; | |
| 47 | 47 | end. | |
| 48 | 48 | ``` | |
| 49 | 49 | ||
| 50 | 50 | The global variable `i` is modified by calling `foo`. The program runs an [[Infinite loop|infinite loop]]. | |
| 51 | 51 | ||
| 52 | 52 | #### type restrictions | |
| 53 | 53 | ||
| 54 | 54 | The [[Data type|type]] of `controlVariable` has to be enumerable. Assuming your system operates on [[ASCII]] you can do | |
| 55 | 55 | ``` | |
| 56 | 56 | var | |
| 57 | 57 | c: char; | |
| 58 | 58 | begin | |
| 59 | 59 | for c := 'a' to 'z' do | |
| 60 | 60 | begin | |
| 61 | 61 | writeLn(c); | |
| 62 | 62 | end; | |
| 63 | 63 | end. | |
| 64 | 64 | ``` | |
| 65 | 65 | ||
| 66 | 66 | or generally use any type that is enumerable. | |
| 67 | 67 | ||
| 68 | 68 | #### other step widths | |
| 69 | 69 | ||
| 70 | 70 | Other 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`. | |
| 71 | 71 | ||
| 72 | 72 | The 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. | |
| 73 | 73 | ||
| 74 | 74 | See also [FPC issue 25549](<https://gitlab.com/freepascal.org/fpc/source/-/issues/25549>). | |
| 75 | 75 | ||
| 76 | 76 | ### limits | |
| 77 | 77 | ||
| 78 | 78 | 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_. | |
| 79 | 79 | ``` | |
| 80 | 80 | for i := 5 to 5 do | |
| 81 | 81 | begin | |
| 82 | 82 | writeLn(i); | |
| 83 | 83 | end; | |
| 84 | 84 | ``` | |
| 85 | 85 | ||
| 86 | 86 | 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]. | |
| 87 | 87 | ||
| 88 | 88 | ### Loop Completion | |
| 89 | 89 | ||
| 90 | 90 | 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. | |
| 91 | 91 | ||
| 92 | 92 | 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. | |
| 93 | 93 | ||
| 94 | 94 | ### short syntax | |
| 95 | 95 | ||
| 96 | 96 | For _single_ statements writing a surrounding `begin` … `end` frame can be skipped resulting in: | |
| 97 | 97 | ``` | |
| 98 | 98 | for controlVariable := start to final do | |
| 99 | 99 | statement; | |
| 100 | 100 | ``` | |
| 101 | 101 | ||
| 102 | 102 | 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. | |
| 103 | 103 | ||
| 104 | 104 | 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). | |
| 105 | 105 | ||
| 106 | 106 | ## loop with elements | |
| 107 | 107 | ||
| 108 | 108 | With [[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. | |
| 109 | 109 | ``` | |
| 110 | 110 | type | |
| 111 | 111 | furniture = (chair, desk, bed, wardrobe); | |
| 112 | 112 | arrangement = set of furniture; | |
| 113 | 113 | var | |
| 114 | 114 | thing: furniture; | |
| 115 | 115 | begin | |
| 116 | 116 | writeLn('all available pieces of furniture:'); | |
| 117 | 117 | for thing in arrangement do | |
| 118 | 118 | begin | |
| 119 | 119 | writeLn(thing); | |
| 120 | 120 | end; | |
| 121 | 121 | end. | |
| 122 | 122 | ``` | |
| 123 | 123 | ||
| 124 | 124 | 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. [[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. | |
| 125 | 125 | ||
| 126 | 126 | ## special commands | |
| 127 | 127 | ||
| 128 | 128 | Inside 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). | |
| 129 | 129 | ||
| 130 | 130 | 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. | |
| 131 | 131 | ||
| 132 | 132 | ## see also | |
| 133 | 133 | ||
| 134 | 134 | * [[Example: Why the loop variable should be of signed type]] | |
| 135 | - | ||
| 135 | + | * [[sRangechecks|`{$rangechecks}`]] | |
| 136 | 136 | ||
| 137 | 137 | ||
| 138 | 138 | **Keywords:** [[Begin|begin]] — [[Do|do]] — [[Else|else]] — [[End|end]] — for — [[If|if]] — [[Repeat|repeat]] — [[Then|then]] — [[Until|until]] — [[While|while]] | |
| 139 | 139 | ||
| 140 | 140 | --- | |
| 141 | 141 | *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).* |
