Course contentsShow
← C
Lesson 281 of 1,2194. Control FlowFree lesson

Pitfall: condition check occurs after execution

Pitfall: condition check occurs after execution

What you'll learn: Why the do-while loop is risky because it forces the code to run at least once before checking if it should have started at all.

The "Shoot First, Ask Questions Later" Loop

Most control structures in C are cautious. An if statement or a while loop checks a condition at the very beginning. If the condition is false, the code inside is skipped entirely. The do-while loop is the rebel of the family. It executes the body of the loop first, and only then looks at the condition to see if it should repeat.

Think of it like a restaurant that serves you a mystery dish and only asks if you have allergies after you’ve taken the first bite. If you are allergic, the damage is already done.

When Logic Fails

This "execute first" behavior can lead to bugs if your program assumes certain requirements are met before the code runs. If your loop body performs a sensitive action—like dividing by a number or accessing a file—the do-while loop will perform that action even if the data is invalid.

Consider this example where we want to process a user's bank balance, but only if they have money:

#include <stdio.h>

int main() {
    int balance = -50; // The user is in debt!

    do {
        printf("Processing your balance of $%d...\n", balance);
        balance -= 10; // Deducting a service fee
    } while (balance > 0);

    printf("Final balance: %d\n", balance);
    return 0;
}

In a standard while loop, this code would do nothing because -50 is not greater than 0. However, the do-while loop forces the "Processing" message to print and deducts a fee, leaving the user with -60. The condition check happened too late to save the program from processing invalid data.

Why This Matters

The pitfall here is assumption. When writing a do-while loop, you are essentially promising the compiler: "It is safe to run this code at least once, no matter what the variables contain."

If your code relies on a specific state (like a pointer not being null or a sensor reading being within range), a do-while loop can crash your program or corrupt data before the condition check even has a chance to stop it. Always ask yourself: "Is it okay if this code runs even if the condition is false?" If the answer is no, a standard while loop is your safest bet.

Key takeaway

A do-while loop always executes its body at least once, which can lead to errors if the initial conditions are invalid.