C++ Break and Continue
Break and continue are statements that change how a loop runs. Break ends a loop, and continue skips the rest of one run.
Break stops a loop
The loop counts toward 5. The break statement ends the loop when the counter reaches 4.
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 4) {
break;
}
std::cout << i << std::endl;
}
return 0;
}Continue skips a value
The loop counts from 1 to 5. The continue statement skips the run for 3.
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
std::cout << i << std::endl;
}
return 0;
}Break leaves a while loop early
The while loop counts toward 10. The break statement ends the loop when the counter reaches 4.
#include <iostream>
int main() {
int count = 1;
while (count <= 10) {
if (count == 4) {
break;
}
std::cout << count << std::endl;
count++;
}
return 0;
}Example
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue;
}
if (i > 5) {
break;
}
std::cout << i << std::endl;
}
return 0;
}Key points
- The break statement ends a loop at once.
- The continue statement skips the rest of the current run.
- After continue, the loop moves on to its next run.
- An if statement often decides when break or continue runs.
- Break can end a while loop before its condition turns false.
In this example, continue skips the run for 3. Break ends the loop after 5 is printed. The loop never reaches the numbers above 5.
Note
Continue does not end a loop. The loop keeps running.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does continue do inside a loop?