Keil Logo


Information in this article applies to:

  • Keil MDK All Versions
  • C166 All Versions
  • C251 All Versions
  • C51 All Versions


How does the do while C statement work?


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);


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.


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

   char c;

   do {
      c = input_char();
   } 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

   int device_id)
   do {
   } 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)
    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.


Last Reviewed: Tuesday, December 1, 2020

Did this article provide the answer you needed?
Not Sure
  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

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.