Jump to: navigation, search

The do loop is a loop that:

  1. Evaluates its statements
  2. Tests a condition
  3. Goes back to number 1 if the condition is true

The syntax of a do loop is

do statement while(condition);

Here are some do statements:

/* read a C identifier after we have the first character */
do
    *wordp++ = c
while ((c = getchar()) != EOF && (isalnum(c) || c == '_')); 

a = 4;
i = 20;
do { /* Go until a and i are equal */
    a++;
    i--;
} while (a != i);

Note that the following does not work:

/* read a C identifier after we have the first character */
do
    *wordp++ = c; /* WRONG */
while ((c = getchar()) != EOF && (isalnum(c) || c == '_')); 

The semicolon after the assignment terminates the do statement. If a compiler's rules allow a do to exist without a respective while, the while loop will eat either the entire identifier or the entire input, whichever comes first. This is bad if

do
    i++;
while (1);

Note that although the correct form of the above is allowed by the C grammar, it is not by many compilers, such as GCC.

Personal tools