While 语句 (C)while Statement (C)

利用 while 语句,您可以重复语句直到指定的表达式变为 false。The while statement lets you repeat a statement until a specified expression becomes false.


while ( expression ) statementwhile ( expression ) statement

expression 必须具有算法或指针类型。The expression must have arithmetic or pointer type. 执行过程如下所示:Execution proceeds as follows:

  1. 计算 expression。The expression is evaluated.

  2. 如果 expression 最初为 false,则绝不执行 while 语句体,并且控制从 while 语句到程序中下一语句的传递。If expression is initially false, the body of the while statement is never executed, and control passes from the while statement to the next statement in the program.

    如果 expression 为 true(非零),则执行语句体,并且此过程从第 1 步开始重复。If expression is true (nonzero), the body of the statement is executed and the process is repeated beginning at step 1.

    while 语句还可在执行语句体中的 break、gotoreturn 时终止。The while statement can also terminate when a break, goto, or return within the statement body is executed. 使用 continue 语句可在不退出 while 循环的情况下终止迭代。Use the continue statement to terminate an iteration without exiting the while loop. continue 语句将控制传递给 while 语句的下一个迭代。The continue statement passes control to the next iteration of the while statement.

    以下是 while 语句的示例:This is an example of the while statement:

while ( i >= 0 )   
    string1[i] = string2[i];  

此示例将 string2 中的字符复制到 string1This example copies characters from string2 to string1. 如果 i 大于或等于 0,则 string2[i] 将赋给 string1[i],并且 i 将递减。If i is greater than or equal to 0, string2[i] is assigned to string1[i] and i is decremented. i 达到 0 或小于 0 时,while 语句的执行将终止。When i reaches or falls below 0, execution of the while statement terminates.

另请参阅See Also

while 语句 (C++)while Statement (C++)