The break and continue statements are used to control loop execution. Both are valid inside loops, but they cannot be used arbitrarily outside a loop or switch where the language permits them.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
if (i == 5)
{
break;
}
printf("%d\n", i);
}
return 0;
}
Example Output #
1
2
4
Explanation #
When i is 3, continue skips the remaining statements in the current iteration:
if (i == 3)
{
continue;
}
Execution then proceeds with the next iteration of the for loop.
When i is 5, break immediately terminates the loop:
if (i == 5)
{
break;
}
Therefore, 5 is not printed.
Both statements are valid here because they occur inside a for loop.
An example such as this is invalid:
if (i == 3)
{
break;
}
when the if statement is not contained within a loop or switch. A break statement must be within an enclosing iteration statement or switch. A continue statement must be within an enclosing iteration statement.