Sign in Join
Wiki copytemporary

While: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: While

OldNewLine
1+`while` in conjunction with [[Do|do]] repeats a statement as long as a condition evaluates to [[True|true]]. The condition [[expression]] is evaluated prior each iteration, determining whether the following [[statement]] is executed. This is the main difference to a [[Repeat|repeat … until-loop]], where the [[Loops|loop]] body is executed at any rate, but succeeding iterations do not necessarily happen, though.
2+
3+The following example contains unreachable code:
4+
5+``` pascal
6+program whileFalse(input, output, stderr);
7+
8+begin
9+ while false do
10+ begin
11+ writeLn('never gets printed');
12+ end;
13+end.
14+```
15+
16+You usually use `while`-loops where, in contrast to [[For|for-loops]], a running index [[Variable|variable]] is not required, the statement executed can't be deduced from an index that's incremented by one, or to avoid a [[Break|break-statement]] (which usually indicates bad programming style).
17+
18+``` pascal
19+program whileDemo(input, output, stderr);
20+
21+var
22+ x: integer;
23+begin
24+ x := 1;
25+
26+ // prints non-negative integer powers of two
27+ while x < high(x) div 2 do
28+ begin
29+ writeLn(x);
30+ inc(x, x); // x := x + x
31+ end;
32+end.
33+```
34+
35+## see also
36+
37+- [[Infinite loop]]
38+
39+---
40+*From the Free Pascal wiki, page "While", as it stood on 2023-01-25 after a change by Kai Burghardt, 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).*
41+Category: Code

Back to history