Loops

A loop statement allows you to execute a statement multiple times. Two loop statements, for and while, test at the top of the loop. The do statement tests at the bottom, thereby ensuring that the loop body executes at least once. This section describes the loop statements. See Section 4.6 for additional statements that affect or control loop execution.

A loop statement can declare variables in the scope of the loop’s substatement. Every time the loop iterates, it reenters the substatement scope. This means objects that are declared in the substatement (and in the loop’s condition) are created and destroyed with every loop iteration.

while Statements

A while statement repeats a statement while a condition is true. The syntax is:

while (condition ) statement

The condition is evaluated and converted to bool. If the value is true, statement is executed, and the loop repeats. If the value is false, the loop finishes and execution continues with the subsequent statement. Thus, if condition is false the first time it is evaluated, the statement is never executed.

A continue statement in a while loop branches to the top of the loop, and execution continues with the evaluation of condition. A break statement exits immediately.

A while loop is typically used for unbounded iteration, that is, when you don’t know beforehand how many times a loop will iterate. Example 4-5 shows how the while loop can be used to control I/O.

Example 4-5. Controlling I/O with the while loop
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <string>
#include <vector>

// Sort lines of text.
int main(  )
{
  using namespace std;
  string line;
  vector<string> data;  while (getline(cin, line))
    data.push_back(line);
  sort(data.begin(  ), data.end(  ));
  copy(data.begin(  ), data.end(  ),
    ostream_iterator<string>(cout, "\n"));
}

for Statements

A for loop is a generalization of the traditional counted loop that appears in most programming languages. The syntax for a for loop is:

for (init ; condition ; iterate-expr ) statement

The init, condition, and iterate-expr parts are optional. The init part of the for statement can be an expression or a simple declaration. The init part offers more flexibility than a condition. While a condition can declare only one name, the init part can declare multiple names. The syntax for the init part is:

specifier-list declarator-list

or:

expression

As with the condition, the scope of the init part extends to the end of statement. The init, condition, and iterate-expr parts are in the same scope as the loop body. See Chapter 2 for more information about specifiers and declarators.

The for loop starts by executing the init part, if present. It then evaluates the condition (just like a while loop). If the condition is true, the loop executes statement. It then evaluates iterate-expr and reevaluates condition. This process continues while condition is true. If condition is false, the loop finishes and execution continues with the subsequent statement. Thus, the init part is evaluated exactly once. The condition is evaluated at least once. The statement might be executed zero times.

The most common use of a for loop is to count a bounded loop, although its flexibility makes it useful for unbounded loops, too, as you can see in Example 4-6.

Example 4-6. Multiple uses of for loops
// One way to implement the for_each standard algorithm
template<typename InIter, typename Function>
Function for_each(InIter first, InIter last, Function f)
{  for ( ; first != last; ++first)
    f(*first);
  return f;
}

// One way to implement the generate_n standard algorithm
template<typename OutIter, typename Size, typename Generator>
void generate_n(OutIter first, Size n, Generator gen)
{
  for (Size i = 0; i < n; ++i, ++first)
    *first = gen;
}

A continue statement in a for loop branches to the top of the loop, and execution continues by evaluating the iterate-expr and then the condition. A break statement exits the loop without evaluating the iterate-expr. See Section 4.6 later in this chapter for examples of break and continue.

The init, condition, and interate-expr parts are all optional. If the init or iterate-expr parts are omitted, nothing happens to initialize the loop or after the statement executes. If the condition is omitted, it defaults to true.

do Statements

The do statement is like a while statement, except that it tests at the end of the loop body. The syntax is:

dostatement while ( expression ) ;

The statement is executed, then the expression is evaluated and converted to bool. If the value is true, the statement is repeated and the expression is checked again. If the expression is false, the loop finishes and execution continues with the subsequent statement. Thus, statement is always executed at least once.

A continue statement in a do loop jumps to the end of statement, and execution continues with the evaluation and test of expression. A break statement exits immediately.

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.