The while statement

A while statement repeatedly runs the body of a loop until the controlling expression evaluates to false (or 0 in C).

Read syntax diagramSkip visual syntax diagramwhile statement syntax

C The expression must be of arithmetic or pointer type. C++The expression must be convertible to bool.

The expression is evaluated to determine whether or not to process the body of the loop. If the expression evaluates to false, the body of the loop never runs. If the expression does not evaluate to false, the loop body is processed. After the body has run, control passes back to the expression. Further processing depends on the value of the condition.

A break, return, or goto statement can cause a while statement to end, even when the condition does not evaluate to false.

C++ A throw expression also can cause a while statement to end prior to the condition being evaluated.

In the following example, item[index] triples and is printed out, as long as the value of the expression ++index is less than MAX_INDEX. When ++index evaluates to MAX_INDEX, the while statement ends.

 ** This example illustrates the while statement.

#define MAX_INDEX  (sizeof(item) / sizeof(item[0]))
#include <stdio.h>

int main(void)
   static int item[ ] = { 12, 55, 62, 85, 102 };
   int index = 0;

   while (index < MAX_INDEX)
      item[index] *= 3;
      printf("item[%d] = %d\n", index, item[index]);