Home

while Loop Statement

Simple while (expression) Statement

This is the simplest conditional (i.e. not infinite) loop statement. The parantheses around expression are mandatory. If expression evaluates to zero or false before the first pass through the loop, the statement or block following will not be executed at all.

C++ is a free-form language, so all of the following are equivalent. The last form is strongly recommended.

while (a < b) DoSomething();

while (a < b)
  DoSomething();

while (a < b) { DoSomething(); }

while (a < b)
{
  DoSomething();
}

Extended do .. while (expression) Statement

C++'s do .. while (expression) statement is similar to Pascal's REPEAT .. UNTIL expression statement. The parantheses around the boolean expression are mandatory. The statement or block between do and while (expression) will always be executed at least one time. The loop cycles again if expression evaluates to nonzero or true and terminates if expression evaluates to zero or false.

C++ is a free-form language, so all of the following are equivalent. The last form is strongly recommended.

do DoSomething() while (a < b);

do
  DoSomething();
while (a < b);

do { DoSomething(); } while (a < b);

do
{
  DoSomething();
}
while (a < b);

Home


Questions or comments to phil@munts.net