C Continue Statement
The continue statement in C is used to skip the current iteration of a loop and proceed with the next iteration. When a continue statement is encountered, the remaining code inside the loop is ignored for the current iteration, and the control moves to the next iteration of the loop.
1. Continue Statement Syntax
The continue statement can be placed inside any loop. When executed, it immediately skips to the next iteration of the loop, effectively bypassing the remaining statements in the loop for that iteration.
Syntax:
// Inside loop
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skips the rest of the loop body when i is 5
}
// Other code
}
// Inside while loop
while (condition) {
if (condition_to_skip) {
continue; // Skips to the next iteration when condition_to_skip is true
}
// Other code
}
Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skips printing 5
}
printf("%d\n", i);
}
return 0;
}
Output:
0
1
2
3
4
6
7
8
9
1
2
3
4
6
7
8
9
2. Key Points of the Continue Statement
- The continue statement skips the current iteration of the loop and proceeds with the next iteration.
- When used inside a loop, it causes the loop to immediately jump to the next iteration, ignoring the rest of the code in that iteration.
- The continue statement only affects the innermost loop it is placed in, and it does not exit the loop or affect the outer loops.
3. Common Use Cases for the Continue Statement
- Use continue when you want to skip specific iterations of a loop based on a condition (e.g., skipping even numbers).
- It is particularly useful for avoiding unnecessary code execution or filtering out unwanted values without breaking the loop.
4. Example of Continue in a For Loop
The following example demonstrates the use of continue in a for loop, where we skip printing the number 5.
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skip printing 5
}
printf("%d\n", i);
}
return 0;
}
Output:
0
1
2
3
4
6
7
8
9
1
2
3
4
6
7
8
9
5. Key Considerations
- Use the continue statement sparingly, as excessive use can make the loop logic harder to follow and understand.
- When using continue in nested loops, it only affects the innermost loop. If you need to affect outer loops, consider using flags or restructuring the loop.