range-for, break and continue
A loop with a counter is handy when you need positions: 0, 1, 2 and so on. But to add up the numbers 3, 1, 4, 1 and 5, you need the values themselves, not their positions. For this, there is the range-for loop: it puts each value from a list into a variable, one after another.
#include <initializer_list>
#include <iostream>
int main() {
int sum = 0;
for (int x : {3, 1, 4, 1, 5}) {
sum = sum + x;
}
std::cout << sum << '\n'; // 14
}Looping over a range
The header of such a loop holds a variable declaration, a colon and a range. Here the range is a list of values in curly braces. The body runs once for each value: first x is 3, then 1, and so on. On every iteration, x is a new variable that holds a copy of the next value.
There is no counter, condition or step, so there is no room for an off-by-one error. The compiler turns a list in curly braces into an object of the standard type std::initializer_list. The line #include <initializer_list> brings in its declaration.
break
The break statement ends the loop at once: the rest of the body and all later iterations are skipped. This loop looks for the first number above 50 that is divisible by 7 and stops there:
for (int i = 51; i <= 100; ++i) {
if (i % 7 == 0) {
std::cout << i << '\n'; // 56
break;
}
}Without break, the loop would print every such number up to 100: 56, 63, 70 and so on up to 98.
continue
The continue statement skips the rest of the body and moves on to the next iteration. In a for loop with a counter, the step still runs after continue, and then the condition is checked. This is how even numbers are left out of a sum:
int sum = 0;
for (int x : {3, 8, 1, 6, 5}) {
if (x % 2 == 0) {
continue;
}
sum = sum + x;
}
std::cout << sum << '\n'; // 9For 8 and 6, the condition x % 2 == 0 is true, and the addition is never reached. Only 3, 1 and 5 get into the sum. Both statements, break and continue, work in every kind of loop: for, while, do-while and range-for.
Common mistake
continue in a while loop whose counter is incremented at the end of the body:
int i = 0;
while (i < 5) {
if (i == 2) {
std::cout << "skip\n";
continue; // ✗
}
std::cout << i << '\n';
++i;
}A while loop has no step in its header, so continue jumps over ++i as well. Once i is 2, nothing changes it anymore: i < 5 stays true, and the program prints skip forever. Increment i before continue, or rewrite the loop as a for.