do-while 语句 (C)do-while Statement (C)

利用 do-while 语句,您可以重复语句或复合语句,直到指定的表达式的计算结果为 false。The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.


do statement while ( expression ) ;do statement while ( expression ) ;

在执行循环体后,将计算 do-while 语句中的 expression。The expression in a do-while statement is evaluated after the body of the loop is executed. 因此,总是至少执行一次循环体。Therefore, the body of the loop is always executed at least once.

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

  1. 执行语句体。The statement body is executed.

  2. 接着,计算 expression。Next, expression is evaluated. 如果 expression 为 false,则 do-while 语句将终止,控制将传递到程序中的下一条语句。If expression is false, the do-while statement terminates and control passes to the next statement in the program. 如果 expression 为 true(非零),则将从第 1 步开始重复此过程。If expression is true (nonzero), the process is repeated, beginning with step 1.

    当 break、gotoreturn 语句在语句体中执行时,do-while 语句也会终止。The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body.

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

    y = f( x );  
} while ( x > 0 );  

在此 do-while 语句中,无论 y = f( x ); 的初始值是什么,x--;x 这两个语句都会执行。In this do-while statement, the two statements y = f( x ); and x--; are executed, regardless of the initial value of x. 然后将计算 x > 0Then x > 0 is evaluated. 如果 x 大于 0,则会再次执行语句体并重新计算 x > 0If x is greater than 0, the statement body is executed again and x > 0 is reevaluated. 只要 x 保持大于 0,语句主体就会重复执行。The statement body is executed repeatedly as long as x remains greater than 0. do-while 变为 0 或负值时,x 语句的执行将终止。Execution of the do-while statement terminates when x becomes 0 or negative. 将至少执行一次循环体。The body of the loop is executed at least once.

另请参阅See Also

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