Home

for Loop Statement

The for statement requires three expressions inside parantheses and separated by semicolons:

All of the three expressions are optional, but the semicolons are not.

Infinite Loop

C++ is a free-form language, so the last three of the following forms are equivalent, with the last strongly recommended.

for (;;);  // Stop the program dead in its tracks

for (;;) DoSomething();

for (;;)
  DoSomething();

for (;;)
{
  DoSomething();
}

Counting loop with internal variable

for (int x = 0; x < 10; x++)
{
  DoSomething(x);  // Called with values 0 to 9 but NOT 10
}

// x is now undefined

Counting loop with external variable

int x;

for (x = 1; x <= 10; x++)
{
  DoSomething(x)  // Called with values 1 to 10
}

// x is now 11

Home


Questions or comments to phil@munts.net