Ch3.4: while

The while Statement

A while statement repeats one statement as long as a condition is true.


while (cond)
    ;

Here the body is just an empty statement (;). This loop repeatedly checks the condition but does nothing.

Always Use { }

As with if, beginners should always use braces. Without braces, only one statement belongs to the loop.

❌ Wrong (only one statement is inside the loop)


while (x < 5)
    x = x + 1;
    print("looping\n");   // this is NOT inside the loop

✔️ Correct


while (x < 5) {
    x = x + 1;
    print("looping\n");
}

Braces make it clear which statements repeat.

Dead Loop

A dead loop (infinite loop) is a loop whose condition is always true.


while (true) {
    ;
}

This loop never ends. It is sometimes useful in low-level code, servers, or event loops, but beginners should use it carefully.

You can also write an infinite loop using an init-statement:


while (auto flag = true; flag) {
    ;
}

Init-statement

A while loop may declare a variable before the condition. C++ allows two different ways to write this. The variable exists only inside the loop.

Form 1


::std::uint_least32_t a{3};
::std::uint_least32_t b{9};

while (::std::int_least32_t sum = a + b) {   // condition is: sum != 0
    println("sum != 0, a=", a, ", b=", b, ", sum=", sum);
    break;  // avoid infinite loop in this example
}

In this form, the condition is simply whether the variable is nonzero.

Form 2


while (auto sum = a + b; sum > 10) {
    println("sum > 10, a=", a, ", b=", b, ", sum=", sum);
    break;  // avoid infinite loop in this example
}

In this form, the variable is declared first, and then a separate condition is checked.

In both forms, the variable (sum) is destroyed at the end of each loop iteration.

Example: Summing Numbers in [0, 100)

A common pattern is to loop over a range. In C++, we prefer to write the condition using != instead of < when possible.


::std::uint_least32_t i{};
::std::uint_least32_t sum{};

while (i != 100) {   // preferred over i < 100
    sum = sum + i;
    ++i;
}

println("sum of [0,100) = ", sum);

Using != avoids off-by-one mistakes and makes the loop clearer.

Example: Summing Only Multiples of 3

You can combine while with if to filter values.


::std::uint_least32_t i{};
::std::uint_least32_t sum{};

while (i != 100) {
    if (i % 3 == 0) {
        sum = sum + i;
    }
    ++i;
}

println("sum of multiples of 3 in [0,100) = ", sum);

This pattern is very common: loop over a range, and use if to select values.

Style Note

In C++, we generally prefer:

These conventions make loops easier to read and less error‑prone.

Empty-Body Loops

Sometimes all the work happens in the condition or increment. In such cases, the loop body is intentionally empty:


while (++x < 10)
    ;   // empty body

This is valid, but should be used carefully. Most loops should use { } for clarity.

Key takeaways