C++ Notes
size_t is a type. Any alias that names a type is itself a type.unsigned int, unsigned long, or unsigned long long depending on the system.sizeof() returns, and the type used internally by arrays and containers for indexing.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.
size_t as the loop variable when iterating over sizes or container indices.// 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 (condition) { // runs as long as condition is true } // with iterator size_t i{}; while (i < COUNT) { ++i; // code }
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.
#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; }
| Loop | Condition Checked | Best For |
|---|---|---|
for | Before each iteration | You know how many times to repeat, or you're iterating by index |
while | Before each iteration | You don't know the count ahead of time, repetition depends on a condition that changes elsewhere |
do-while | After each iteration | The body must run at least once no matter what, like input validation prompts |
Three loops, one real difference between them: whether the condition gets checked before the body runs or after. Next up, arrays.