C Break and Continue Statements
Introduction to Break and Continue
The break and continue statements in C are used to alter the normal flow of loops. These statements provide control over loop execution, allowing you to exit loops prematurely or skip certain iterations based on specific conditions.
The Break Statement
The break statement terminates the innermost loop (for, while, or do-while) or switch statement immediately. When encountered, control passes to the statement following the terminated loop or switch.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
printf("Breaking at i = %d\n", i);
break;
}
printf("%d ", i);
}
printf("\nLoop terminated.\n");
return 0;
}
1 2 3 4 Breaking at i = 5 Loop terminated.
The Continue Statement
The continue statement skips the rest of the current iteration of a loop and proceeds to the next iteration. Unlike break, it doesn't terminate the loop entirely but moves to the next cycle.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
printf("Skipping i = %d\n", i);
continue;
}
printf("%d ", i);
}
printf("\nLoop completed.\n");
return 0;
}
1 2 Skipping i = 3 4 5 Loop completed.
Break in Switch Statements
Break is also commonly used in switch statements to prevent fall-through behavior, where execution would continue to the next case without it.
#include <stdio.h>
int main(void) {
int choice = 2;
switch (choice) {
case 1:
printf("Case 1 selected\n");
break;
case 2:
printf("Case 2 selected\n");
break;
case 3:
printf("Case 3 selected\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Case 2 selected
Practical Examples
Break and continue are often used together in real-world scenarios to create more efficient and readable loops.
#include <stdio.h>
int main(void) {
int numbers[] = {2, 5, 4, 9, 8, 11, 10, 3};
int search = 10;
int found = 0;
int len = (int)(sizeof numbers / sizeof numbers[0]);
for (int i = 0; i < len; i++) {
// Skip odd numbers quickly
if (numbers[i] % 2 != 0) {
continue;
}
if (numbers[i] == search) {
printf("Found %d at index %d\n", search, i);
found = 1;
break;
}
printf("Checked %d at index %d\n", numbers[i], i);
}
if (!found) {
printf("%d not found in the array\n", search);
}
return 0;
}
Checked 2 at index 0 Checked 4 at index 2 Checked 8 at index 4 Found 10 at index 6
Comparison Table
Statement | Effect | Use Case |
---|---|---|
break | Exits the loop or switch immediately | When further iteration is unnecessary or a match is found |
continue | Skips to the next iteration | When you want to skip specific cases but continue looping |