Loops
Loops repeat a block while a condition holds. C++ has while, do/while, the C-style for, and range-for. break leaves the loop; continue skips to the next iteration.
Detailed Explanation
You have a list of log lines and you want to count the ones that contain ERROR. That is a loop: do the same work for each line, then stop. C++ offers four shapes. They all compile to a test, a body, and a jump. The difference is where the test lives and how the loop variable is declared.
while (cond) body tests first. If cond is already false, the body never runs. Use it when the number of iterations is not known up front: read until EOF, wait until a flag flips, pop until a stack is empty.
do { body } while (cond); tests after the body. The body runs at least once. That is the right shape for "show the menu, then ask whether to continue". It is the wrong shape when the input might already be empty; you will process a garbage first element.
The C-style for (init; cond; step) body is a while with the counter packaged in one line. init runs once. cond is tested before each iteration. step runs after each iteration, including after continue. C++ extends init so you can declare the variable there: for (int i = 0; i < n; ++i). The variable's scope is the loop, which is what you want.
Range-for (for (auto&& x : seq)) is the default when you have a container or any type with begin/end. It is a separate entry because it hides the iterators and the off-by-one. Prefer it unless you need the index or you are mutating the container's shape while iterating.
break exits the innermost loop. It does not take a label in standard C++ (unlike Java). To leave two nested loops, use a flag, extract a function and return, or (rarely) goto. continue jumps to the step of a for, or to the condition of a while, skipping the rest of the body.
Infinite loops are written for (;;) or while (true). You still need an exit: break, return, throw, or std::exit. A loop the compiler can prove never ends, with no side effects, is undefined behaviour; a loop that waits on I/O or an atomic is fine.
Cost is the body, not the construct. A tight for over an index and a range-for over a std::vector generate the same pointer walk. A range-for over std::map walks nodes. Do not convert a range-for to an index loop for speed unless you have measured and you needed the index anyway.
Off-by-one errors live in the condition. i <= n on a 0-based array of n elements overruns. i != end on iterators is the STL style and stays correct if you only increment. Unsigned loop variables that decrement toward zero need care: for (unsigned i = n; i-- > 0;) is a known idiom; for (unsigned i = n; i >= 0; --i) never ends.
Code Examples
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums{1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
sum += nums[static_cast<std::size_t>(i)];
}
std::cout << sum << '\n'; // prints: 15
int n = 3;
while (n > 0) {
std::cout << n << ' ';
--n;
}
std::cout << '\n'; // prints: 3 2 1
}#include <iostream>
#include <string>
int main() {
std::string line;
// Pretend we read lines; here we walk a fixed list.
for (const char* sample : {"ok", "ERROR disk", "ok"}) {
if (std::string(sample).find("ERROR") == std::string::npos) {
continue; // skip non-errors
}
std::cout << sample << '\n'; // prints: ERROR disk
break; // stop at the first error
}
}Common Gotchas
Modifying a container you are ranging over
inserting or erasing inside `for (auto& x : v)` can invalidate the hidden iterators. Use an iterator loop that reseats on erase, or collect indices and edit afterwards.
Unsigned countdown
`for (std::size_t i = v.size() - 1; i >= 0; --i)` wraps and loops forever when `i` is `0` and you `--i`. Walk forward, or use signed indices, or `i-- > 0`.
`for (int i = 0; i < v.size(); ++i)` mixes signed and unsigned
`v.size()` is `size_t`. Enable conversion warnings, or iterate with `std::size_t`, or use range-for.
`continue` in a `for` still runs the step
`for (int i = 0; i < 10; ++i) { if (i == 3) continue; }` does increment `i`. You cannot skip the `++i` with `continue`.