Skip to content

Do-While Loops

Do-While loops are designed to do something until a certain condition evaluates to false, but at least execute the action once. This means, that a do-while loop could also run infinitely when the condition never gets fulfilled.
Like the if statement, the condition of the do-while loop must evaluate to a boolean value, but can hold complex, nested expressions.


Here is an example of a simple do-while loop:

int counter = 0;
do {
    printf("Loop run %d", counter);
} while counter < 20;

Optional parentheses

As with the if statement, for loop and foreach loop, the parentheses around the head of the do-while loop are optional.

If you wanted to intentionally achieve an endless loop, you would write something like this:

do {
    printf("This is gonna run forever ...");
} while true;

Usage of loop alternatives

If you somehow know how many times you want to execute something, we recommend you to use a for loop instead. If you want to iterate over a container of items, consider using the foreach loop.