For Loop Fundamentals
Lesson outline
Understanding the For Loop
The for loop is a compact looping construct in C++ that repeats a statement or block for a controlled number of iterations.
It has three parts: initialization, condition, and iteration. The condition is checked before each iteration; the iteration expression runs after the loop body. Variables declared in the initialization part have scope limited to the loop.
Detailed Syntax Breakdown
Full Syntax & Variations
General form: for ( init-statement ; condition ; iteration ) statement;
Each part is optional; omitting the condition makes it true.
Range-Based For (C++11+)
For iterating containers and arrays, prefer the range-based for loop for clarity and safety.
Indexing Containers Safely
When indexing standard containers, prefer std::size_t (the type returned by size()) to avoid signed/unsigned comparison issues.
Common Patterns
Erasing While Iterating (Containers)
Erasing elements invalidates iterators for many containers. Use the erase-return pattern or erase/remove_if.
Debugging Tips
- 🔹 Ensure the loop condition will eventually become false (avoid infinite loops).
- 🔹 Watch for off-by-one errors (
<vs<=). - 🔹 Initialize variables before use; keep loop state local to the loop when possible.
- 🔹 Avoid modifying the loop counter inside the body.
- 🔹 Avoid floating-point loop counters for index logic—precision can cause missed termination.
- 🔹 Prefer range-based
forfor containers/arrays when you don't need the index.