6.7. The while Statement6.7. while 语句A while statement repeatedly executes a target statement as long as a condition is true. Its syntactic form is 当条件为真时,while 语句反复执行目标语句。它的语法形式如下: 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. 只要条件 condition 的值为 true,执行语句 statement(通常是一个块语句)。condition 不能为空。如果第一次求解 condition 就产生 false 值,则不执行 statement。 The condition can be an expression or an initialized variable definition: 循环条件 condition 可以是一个表达式,或者是提供初始化的变量定义。 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. 在循环条件中定义的任意变量都只在与 while 关联的块语句中可见。每一次循环都将该变量的初值转换为 bool(第 5.12.3 节)。如果求得的值为 true,则执行 while 的循环体。通常,循环条件自身或者在循环体内必须做一些相关操作来改变循环条件表达式的值。否则,循环可能永远不会结束。
Using a while Loopwhile 循环的使用We have already seen a number of while loops, but for completeness, here is an example that copies the contents of one array into another: 前面的章节已经用过很多 while 循环,但为更完整地了解该结构,考虑下面将一个数组的内容复制到另一个数组的例子: // 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. 首先初始化 source 和 dest,并使它们各自指向所关联的数组的第一个元素。while 循环条件判断是否已经到达要复制的数组的末尾。如果没有,继续执行循环。循环体只有单个语句,实现元素的复制,并对两个指针做自增操作,使它们指向对应数组的下一个元素。 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 正如 第 5.5. 节提出的关于“简洁即是美”的建议,C++ 程序员应尝试编写简洁的表达式。while 循环体中的语句: *dest++ = *source++; is a classic example. This expression is equivalent to 是一个经典的例子。这个表达式等价于: { *dest = *source; // copy element ++dest; // increment the pointers ++source; }
|