Main Index : Reference :

do - while


Description

Repeats a piece of code as long as an expression is true.

Usage

while (expression)
{
  // Do stuff
}
do
{
  // Do stuff
}
while (expression);

Program Structure

A do and while structure repeats a code block as long as expression is true. A true expression is an expression that's not 0 or nil. There are two ways to use the statements, as seen above. The difference lies in when the expression is first evaluated. With just a while block, the expression is evaluated before the first loop. With the do-while construction, the code block following do is always executed once before the expression is even evaluated. The loop ends when expression is false.

If the code to be executed is only one line, one doesn't have to include the enclosing braces, {}.

The expression often consists of comparison operators, such as ==, !=, >, >=, < and <=. These can in turn be combined with logical operators, such as &&, ! and ||. You can read more about these operators here.

Example

// This loop will run ten times, until x is 10.

var x = 0;

while (x<10)
{
  doStuff(x);
  x = x+1;
}


// Even though x is 5, this loop will run one time before
// it "realizes" that the expression is false.

var x = 5;

do
{
  doStuff(x);
}
while(x!=5)


// while loops can be used to find an element of 
// a specific type in a linked list.
//
// Afterwards, tag will contain the first texture tag 
// of the object, or null if there are none.

var tag = obj->GetFirstTag();

while(tag && tag->GetType()!=TAG_TEXTURE) 
  tag = tag->GetNext(); 

See Also

Operators