C++ — Continue and guarded iteration
continue skips the rest of a loop iteration. In a range-based for loop traversal resumes with the next element if one remains.
A simple example
Skip just the number 2
- Start with Visit 1 through 3
- Do this Skip 2
- Result 1 → 3
#include <iostream>
int main() {
for (int n = 1; n <= 3; n++) {
if (n == 2) {
continue;
}
std::cout << (n) << '\n';
}
}
1 3
Exclude invalid readings while keeping zero
Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. Placing the guard first keeps invalid readings out of both updates. A measured zero must still increment the count.
A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.
Run the example
Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
#include <iostream>
int main() {
int count = 0;
int sum = 0;
for (int reading : {-2, 0, 4, -1, 6}) {
if (reading < 0) continue;
++count;
sum += reading;
}
std::cout << count << " readings, sum " << sum << '\n';
return 0;
}
3 readings, sum 10
The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.
Try it yourself
Append −3 and then 0. What should the count and sum become?
Check your answer
The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.