Loops normally execute until their condition becomes false. However, sometimes a program needs to stop a loop early or skip a particular iteration. In C, this is done using the break and continue statements.
These statements provide better control over loop execution.
1. break Statement
The break statement immediately terminates the loop and transfers control to the statement following the loop.
Example Program
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
{
break; // Terminate the loop immediately
}
printf("%d\n", i);
}
return 0;
}
How It Works
The loop starts executing normally from 1. When the value of i becomes 5, the break statement executes immediately and terminates the loop. Control then moves to the first statement after the loop.
Console Output
1
2
3
4
Execution Flowchart
2. continue Statement
The continue statement skips the current iteration and moves directly to the next iteration of the loop.
Example Program
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 5; i++)
{
if(i == 3)
{
continue; // Skip the remaining code, move directly to next iteration
}
printf("%d\n", i);
}
return 0;
}
How It Works
When i becomes 3, the continue statement skips the remaining code inside the loop for that iteration. The loop then proceeds directly to the next iteration.
Console Output
1
2
4
5
Execution Flowchart
Key Differences
Understanding the key structural and operational differences between these two statement types:
| Statement | Purpose |
|---|---|
| break | Terminates the loop completely |
| continue | Skips the current iteration |
Embedded Focus
break and continue are commonly used in embedded systems for handling errors, filtering sensor data, and controlling hardware behavior efficiently.
while(1)
{
if(error_detected)
{
break;
}
if(sensor_value < 0)
{
continue;
}
process_data();
}
In embedded firmware, these statements help control program flow efficiently while continuously monitoring hardware and system conditions.