C Break and Continue
The break and continue statements give you extra control inside loops. break stops a loop early, while continue skips the rest of the current pass and jumps to the next one.
The break Statement
The break statement immediately ends the loop it is inside, even if the loop condition is still true. The program then continues with the code after the loop. This is handy when you have found what you were looking for and no longer need to keep looping.
Stopping a loop with break
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("i is %d\n", i);
}
return 0;
}The loop would normally run until i reaches 10, but when i equals 4 the break statement stops it. So this prints only 0, 1, 2, and 3.
The continue Statement
The continue statement skips the rest of the current pass and jumps straight to the next one. Unlike break, it does not end the loop; it just moves on early.
Skipping a value with continue
#include <stdio.h>
int main() {
for (int i = 0; i < 6; i++) {
if (i == 3) {
continue;
}
printf("i is %d\n", i);
}
return 0;
}When i equals 3, continue skips the printf and goes to the next pass. So the output shows 0, 1, 2, 4, and 5, with 3 missing.
Exercise: C Break and Continue
What does the break statement do when executed inside a loop?