Ch3.5: for

The for Statement

A for loop is another way to repeat a statement. It has three parts:


for (init; cond; step) {
    body
}

As before, ; can be an empty statement if the body does nothing.


        ┌───────────────┐
        │     init       │   (runs once)
        └───────┬───────┘
                │
                ▼
        ┌───────────────┐
┌────▶│     cond       │─── false ───▶ loop ends
│     └───────┬───────┘
│             │ true
│             ▼
│     ┌───────────────┐
│     │     body       │
│     └───────┬───────┘
│             │
│             ▼
│     ┌───────────────┐
└─────│      step      │
        └───────┬───────┘
                │
                └─────────────── back to cond

Always Use { }

As with if and while, beginners should always use braces.

❌ Wrong


for (i = 0; i != 5; ++i)
    print(i, "\n");
    print("done\n");   // NOT inside the loop

✔️ Correct


for (i = 0; i != 5; ++i) {
    print(i, "\n");
}
print("done\n");

Init-statement

A for loop may declare a variable in the init part.


for (::std::int_least32_t i = 0; i != 5; ++i) {
    println("i=", i);
}

The variable (i) exists only inside the loop.

Example: Summing Numbers in [0, 100)

A for loop is ideal for iterating over a range.


::std::uint_least32_t sum{};

for (::std::uint_least32_t i{}; i != 100; ++i) {
    sum = sum + i;
}

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

As before, we prefer != for fixed limits.

Example: Summing Only Multiples of 3

You can combine for with if to filter values.


::std::uint_least32_t sum{};

for (::std::uint_least32_t i{}; i != 100; ++i) {
    if (i % 3 == 0) {
        sum = sum + i;
    }
}

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

Dead Loop

A dead loop (infinite loop) can be written using for:


for (;;) {
    ;
}

All three parts are omitted, so nothing stops the loop.

According to the C++ standard, this form behaves the same as:


while (true) {
    ;
}

Both loops run forever unless something inside the body breaks out.

Empty-Body Loops

Sometimes all the work happens in the step expression:


for (::std::uint_least32_t i{}; i != 10; ++i)
    ;   // empty body

This is valid, but should be used carefully.

Style Note

In C++, we generally prefer:

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

Key takeaways