While/Do Loops

The while/do loop is a loop that executes a statement or a block of statements repeatedly, as long as a given condition evaluates to true. The condition will be re-evaluated at the beginning of each iteration of the loop, allowing code inside the loop to affect the condition in order to terminate it.

Since the condition is evaluated before the loop is entered, it is possible for a while/do loop to never be executed even once, if the condition is already false when execution arrives at the loop.

As an alternative to the while/do loop, the repeat/until block loop will evaluate a condition at the end of each iteration, thus providing a loop that is guaranteed to be entered at least once.

Syntax

The basic syntax for a while/do loop looks like this:

while x < 10 do 
  DoSomething();

where a conditional expression is specified between the while and do keywords, and the do keyword is followed by the statement that is to be executed repeatedly.

Nullable Conditions

The condition expression for the while/do loop must be of Boolean or Nullable Boolean type.

If the condition is a simple boolean, the while/do loop will execute as long as the condition evaluates to true.

If the condition is a Nullable Boolean type, then the additional case of the condition evaluating to nil needs to be considered. While a nil nullable boolean strictly speaking is not equivalent to false, the while/do loop treats them the same, and will stop executing the loop if the condition evaluates to either nil or false.

This behavior symmetrically extends to if/then statements and repeat/until loops, which also treat a nil condition as equivalent to false.

while/do Loops and begin/end blocks.

On its own, the while/do loop only takes a single statement to be executed for each iteration. To execute more than one statement, multiple statements can be grouped using a begin/end Block Statement:

while x > 10 do begin
  DoSomething();
  DoSomethingElse();
end;

Prematurely Exiting the Loop or a Loop Iteration

Like all loops, while/do loops can be exited prematurely using the break and exit statements, and a single loop iteration can be cut short by using the continue statement, which jumps to the next loop iteration.

See Also