0
0
CComparisonBeginner · 3 min read

Break vs Continue in C: Key Differences and Usage

In C, break immediately exits the nearest enclosing loop or switch statement, stopping all further iterations. continue skips the rest of the current loop iteration and proceeds to the next iteration without exiting the loop.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of break and continue in C:

Aspectbreakcontinue
PurposeExit the loop immediatelySkip current iteration, continue loop
Effect on loopTerminates loopDoes not terminate loop
UsageInside loops or switchOnly inside loops
Next stepControl moves after loopControl moves to next iteration
Common use caseStop loop on conditionSkip unwanted iteration
⚖️

Key Differences

The break statement in C is used to exit a loop or a switch statement immediately. When break executes, the program jumps out of the nearest enclosing loop or switch, skipping any remaining code inside that loop for the current and future iterations.

On the other hand, continue only skips the rest of the current loop iteration and moves control to the next iteration of the loop. It does not exit the loop entirely. This means the loop keeps running but ignores the code after continue for that iteration.

Another important difference is that break can be used in both loops and switch statements, while continue is only valid inside loops. Using continue in a switch will cause a compilation error.

⚖️

Code Comparison

This example uses break to stop a loop when a number equals 5:

c
#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // Exit loop when i is 5
        }
        printf("%d ", i);
    }
    return 0;
}
Output
1 2 3 4
↔️

Continue Equivalent

This example uses continue to skip printing the number 5 but continues the loop:

c
#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue; // Skip printing 5
        }
        printf("%d ", i);
    }
    return 0;
}
Output
1 2 3 4 6 7 8 9 10
🎯

When to Use Which

Choose break when you want to stop the entire loop early, such as when a condition is met and continuing the loop is unnecessary or incorrect. For example, searching for a value and stopping once found.

Choose continue when you want to skip only the current iteration but keep looping. This is useful to ignore certain cases without stopping the whole process, like skipping invalid inputs but processing the rest.

Key Takeaways

break exits the entire loop immediately.
continue skips only the current iteration and continues looping.
break works in loops and switch; continue only in loops.
Use break to stop looping early when done.
Use continue to skip unwanted iterations but keep looping.