Keil Logo Arm Logo

C: DO WHILE STATEMENT


Information in this article applies to:

  • C166 All Versions
  • C251 All Versions
  • C51 All Versions

QUESTION

How does the do while C statement work?

ANSWER

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

The syntax for a do while statement is:

do loop_body_statement while (cond_exp);

where:

loop_body_statement is any valid C statement or block.

cond_exp is an expression that is evaluated at the end of each pass through the loop. If the value of the expression is "false" (i.e., compares equal to zero) the loop is exited.

Since cond_expr is checked at the end of each pass through the loop, loop_body_statement is always executed at least once, even if cond_expr is false.

The while statement is very similar to do while, except that a while statement tests its cond_exp before each pass through the loop, and therefore may execute its loop_body_statement zero times.

Any of the following C statements used as part of the loop_body_statement can alter the flow of control in a do while statement:

  • break
  • continue
  • goto
  • return

The do while statement is used less often than the other structured loop statements in C, for and while.

Examples

char input_char(void);
void output_char(char);

void
transfer_1_line(void)
{
   char c;

   do {
      c = input_char();
      output_char(c);
   } while (c != '\n');
}

The transfer_1_line function reads characters from input and copies them to output, stopping only after a newline character ('\n') has been copied.

void frob(int device_id);

int frob_status(int device_id);
/* codes returned by frob_status */
#define FROB_FAIL   -1
#define FROB_OK      0


void
frob_to_completion(
   int device_id)
{
   do {
      frob(device_id);
   } while (frob_status(device_id) != FROB_OK);
}

The frob_to_completion function frobs (whatever that means) the specified device until it is frobbed successfully. The device will always be frobbed at least once.

#include <stdio.h>

void prattle (void)
{
  do
    printf("Hello world\n")
  while (1);
}

The prattle function prints "Hello world" forever (or at least until execution of the program is somehow stopped). Although it is easy to write an infinite loop with do while, it is customary to use a while statement instead.

SEE ALSO

Last Reviewed: Thursday, December 15, 2005


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 

Keil logo

Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings