The do Statement

A do loop is simply a while loop turned on its head. First comes the loop body, then the test expression. Unlike a while loop, a do loop always executes its loop body at least once.

Summary: A do loop always executes at least once.

The difference is important. A while statement evaluates the test expression before it executes the loop body. If the test expression in a while statement is false, the loop body doesn't execute at all. A do statement, on the other hand, evaluates the test expression after executing the loop body. Thus, the body of a do statement always executes at least once, even if the test expression is false when the loop begins.

Figure 3.2 contrasts the while loop from WHILE.C with a comparable do loop to emphasize this difference. You'll notice that the do keyword comes right before the loop body, which is followed by the while keyword and a test expression—the same test expression that WHILE.C uses. Notice the semicolon that ends the do loop. A do loop always ends with a semicolon; a while loop never does.

The DO.C program below uses the do loop from Figure 3.2 to perform the same action that WHILE.C does.

/* DO.C: Demonstrate do loop. */

#include <stdio.h>

main()

{

int test = 10;

do

{

printf( "test = %d\n", test );

test = test - 2;

} while( test > 0 );

}

DO.C gives the same output as WHILE.C:

test = 10

test = 8

test = 6

test = 4

test = 2

The programs do not give the same output if you modify them so that the value of test is 0 when the loop starts. In that case, the loop body in DO.C executes once, but the loop body in WHILE.C doesn't execute at all. You should only use a do loop when you always want the loop body to execute at least once.