break exits the nearest loop or switch. continue skips the remaining statements in the current loop iteration and proceeds to the loop update or next condition test.
Both statements are clearest when they shorten exceptional paths. They become difficult to reason about when nested loops contain several exits or when continue bypasses the state change required for progress.
Use break when later iterations cannot improve the result. Keep the result outside the loop so code after the loop can distinguish found from not found.
#include <iostream>
#include <vector>
int main() {
std::vector<int> readings{-1, 12, 18, 42, 50};
for (int value : readings) {
if (value < 0) continue;
std::cout << "checked " << value << '\n';
if (value == 42) break;
}
}
checked 12
checked 18
checked 42
break affects only the nearest loop. For a multi-level search, move the operation into a function and return, store a found flag that the outer condition reads, or use an algorithm such as std::find when it expresses the intent.
continue skips only the invalid row while later rows remain eligible for processing.
#include <iostream>
#include <vector>
int main() {
const std::vector<int> readings{12, -1, 18, -4, 20};
int total = 0;
for (int reading : readings) {
if (reading < 0) continue;
total += reading;
}
std::cout << total << '\n';
}
50
In a <code>while</code> loop, <code>continue</code> jumps directly to the condition. If the counter update sits below it, that update is skipped and the same state repeats forever. Move essential progress before possible <code>continue</code> paths, or use a <code>for</code> loop when its update expression naturally belongs in the header.
<code>break</code> exits only the innermost loop. Put the search in a function and <code>return</code> when the item is found, or use a named boolean checked by the outer loop. An STL algorithm such as <code>std::find</code> can eliminate the nested control flow entirely when the data layout permits it.
Several scattered <code>continue</code> statements can hide which cleanup, counters, or state transitions are skipped.
Explore 500+ free tutorials across 20+ languages and frameworks.