6.7. The while StatementA while statement repeatedly executes a target statement as long as a condition is true. Its syntactic form is while (condition) statement
The statement (which is often a block) is executed as long as the condition evaluates as true. The condition may not be empty. If the first evaluation of condition yields false, statement is not executed. The condition can be an expression or an initialized variable definition: bool quit = false; while (!quit) { // expression as condition quit = do_something(); } while (int loc = search(name)) { // initialized variable as condition // do something } Any variable defined in the condition is visible only within the block associated with the while. On each trip through the loop, the initialized value is converted to bool (Section 5.12.3, p. 182). If the value evaluates as TRue, the while body is executed. Ordinarily, the condition itself or the loop body must do something to change the value of the expression. Otherwise, the loop might never terminate.
Using a while LoopWe have already seen a number of while loops, but for completeness, here is an example that copies the contents of one array into another: // arr1 is an array of ints int *source = arr1; size_t sz = sizeof(arr1)/sizeof(*arr1); // number of elements int *dest = new int[sz]; // uninitialized elements while (source != arr1 + sz) *dest++ = *source++; // copy element and increment pointers
We start by initializing source and dest to point to the first element of their respective arrays. The condition in the while tests whether we've reached the end of the array from which we are copying. If not, we execute the body of the loop. The body contains only a single statement, which copies the element and increments both pointers so that they point to the next element in their corresponding arrays. As we saw in the "Advice" box on page 164, C++ programmers tend to write terse expressions. The statement in the body of the while *dest++ = *source++; is a classic example. This expression is equivalent to { *dest = *source; // copy element ++dest; // increment the pointers ++source; }
|