← Back to all posts

05 C++ Notes

Loops

C++ Notes


size_t

Not ideal when iteration involves negative numbers. Since size_t is unsigned, going below zero causes wrap-around to a huge number instead of a proper negative, which will break loop conditions silently, the loop just keeps running instead of stopping.


For Loop

C++
// standard for loop with size_t
for (size_t i{} ; i < 10 ; ++i) {
    // code runs 10 times
}

// to use the iterator outside the loop, declare it before
size_t i{};
for (i ; i < 10 ; ++i) {
    // code
}
// i is still accessible here

While Loop

C++
while (condition) {
    // runs as long as condition is true
}

// with iterator
size_t i{};
while (i < COUNT) {
    ++i;
    // code
}

Do-While Loop

C++
do {
    // runs first, condition checked after
} while (condition);

Notice the semicolon after the closing while(condition). It's required and easy to forget, since regular while loops and for loops don't have one there.


Code Example: main.cpp

C++
#include <iostream>

int main() {
    std::cout << "sizeof(size_t): " << sizeof(size_t) << '\n'; // prints: 8 on 64-bit systems

    // for loop
    std::cout << "for loop:\n";
    for (size_t i{} ; i < 5 ; ++i) { // size_t: unsigned integer type alias
        std::cout << "i love cpp!\n"; // prints 5 times
    }

    // while loop with boolean flag
    std::cout << "\nwhile loop:\n";
    bool b{true};
    int i{5};
    while (b) {
        --i;
        std::cout << "i love cpp!\n"; // prints 5 times
        b = (i != 0); // when i hits 0, (0 != 0) is false, b becomes false, loop stops
    }

    // do-while: body runs once even though condition is false
    std::cout << "\ndo-while loop:\n";
    do {
        std::cout << "This executes even though condition is false\n\n"; // prints once
    } while (false);

    return 0;
}
Console Output
sizeof(size_t): 8 for loop: i love cpp! i love cpp! i love cpp! i love cpp! i love cpp! while loop: i love cpp! i love cpp! i love cpp! i love cpp! i love cpp! do-while loop: This executes even though condition is false

Which One to Reach For

LoopCondition CheckedBest For
forBefore each iterationYou know how many times to repeat, or you're iterating by index
whileBefore each iterationYou don't know the count ahead of time, repetition depends on a condition that changes elsewhere
do-whileAfter each iterationThe body must run at least once no matter what, like input validation prompts

Closing

Three loops, one real difference between them: whether the condition gets checked before the body runs or after. Next up, arrays.

← Previous 04 - Flow Control Next → 06 - Arrays