While statement
Repeat the statement until the expression evaluates to zero.
grammar
while ( expression ) statement
Remark
The expression test occurs before each execution of the loop; therefore the while loop is executed zero or more times. The expression must be an integer, pointer type, or a class type that contains explicit integer or pointer type conversion.
The while loop can also be aborted when an interrupt, navigation, or regression is executed in the body of the statement. Please use the continue statement to end the current iteration but not exit the while loop. Continue Pass the control to the next loop while.
The following code uses a while loop to cut trailing underscores from a string:
// while_statement.cpp #include <> #include <> char *trim( char *szSource ) { char *pszEOS = 0; // Set pointer to character before terminating NULL pszEOS = szSource + strlen( szSource ) - 1; // iterate backwards until non '_' is found while( (pszEOS >= szSource) && (*pszEOS == '_') ) *pszEOS-- = '\0'; return szSource; } int main() { char szbuf[] = "12345_____"; printf_s("\nBefore trim: %s", szbuf); printf_s("\nAfter trim: %s\n", trim(szbuf)); }
Calculate the termination condition at the top of the loop. If there is no trailing underscore, the loop will not be executed.
do-while statement
Repeat the statement until the specified termination condition (expression) is evaluated to zero.
grammar
do statement while ( expression ) ;
Remark
The test of the terminating condition will be performed after each execution of the loop; therefore the do-while loop will be executed once or more times, depending on the value of the terminating expression. The do-while statement can also terminate when the break, goto, or return statement is executed in the body of the statement.
expression must have an algorithm or pointer type. The execution process is as follows:
Execute the statement body.
Next, calculate the expression. If expression is false, the do-while statement will terminate and control will be passed to the next statement in the program. If expression is true (non-zero), this process will be repeated from the first step.
The following example demonstrates the do-while statement:
// do_while_statement.cpp #include <> int main() { int i = 0; do { printf_s("\n%d",i++); } while (i < 3); }