Infinite loop: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Infinite loop
| Old | New | Line | |
|---|---|---|---|
| 1 | + | An **infinite loop** (also known as an endless loop or unproductive loop or a continuous loop) is a loop which never ends. Inside a loop, [[statement|statements]] are repeated forever. | |
| 2 | + | ||
| 3 | + | There are two implementations of an infinite loop: | |
| 4 | + | ||
| 5 | + | ``` pascal | |
| 6 | + | while true do | |
| 7 | + | begin | |
| 8 | + | // loop body repeated forever | |
| 9 | + | end; | |
| 10 | + | ``` | |
| 11 | + | ||
| 12 | + | ``` pascal | |
| 13 | + | repeat | |
| 14 | + | begin | |
| 15 | + | // loop body repeated forever | |
| 16 | + | end | |
| 17 | + | until false; | |
| 18 | + | ``` | |
| 19 | + | ||
| 20 | + | ## [[Break]] statement | |
| 21 | + | ||
| 22 | + | “[[While]] [[True|true]] [[Do|do]]” or “[[Repeat|repeat]] [[Until|until]] [[False|false]]” loops look infinite at first glance, but there is a way to escape the loop through the `break` statement. | |
| 23 | + | ||
| 24 | + | ``` pascal | |
| 25 | + | var | |
| 26 | + | i:integer; | |
| 27 | + | begin | |
| 28 | + | i := 0; | |
| 29 | + | while true do | |
| 30 | + | begin | |
| 31 | + | i := i + 1; | |
| 32 | + | if i = 100 then break; | |
| 33 | + | end; | |
| 34 | + | end; | |
| 35 | + | ``` | |
| 36 | + | ||
| 37 | + | ``` pascal | |
| 38 | + | var | |
| 39 | + | i:integer; | |
| 40 | + | begin | |
| 41 | + | i := 0; | |
| 42 | + | repeat | |
| 43 | + | i := i + 1; | |
| 44 | + | if i = 100 then break; | |
| 45 | + | until false; | |
| 46 | + | end; | |
| 47 | + | ``` | |
| 48 | + | ||
| 49 | + | ## Optimization | |
| 50 | + | ||
| 51 | + | If you really need an infinite loop, it is better to use `repeat … until false;`, since it shifts all instructions of the body “less” to the right (at least, if there is more than one statement in the loop). | |
| 52 | + | ||
| 53 | + | ## See also | |
| 54 | + | ||
| 55 | + | - [[True|true]] | |
| 56 | + | - [[False|false]] | |
| 57 | + | - [[Repeat|repeat]] [[Until|until]] | |
| 58 | + | - [[While|while]] [[Do|do]] | |
| 59 | + | - [[Break|break]] | |
| 60 | + | - [[Continue|continue]] | |
| 61 | + | ||
| 62 | + | --- | |
| 63 | + | *From the Free Pascal wiki, page "Infinite loop", as it stood on 2023-01-04 after a change by Paskal, out of the wiki's dump of 2024-05-26. 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).* |
