Continue in while vs for loops
What you'll learn: How the continue statement interacts differently with the update step in for loops versus while loops.
The "Skip" Button
The continue statement tells C to stop what it’s doing in the current iteration and jump immediately to the next one. Imagine you are scanning a list of names; when you see one you don't like, you stop reading it and move your finger to the next name.
However, there is a subtle "trap" depending on which type of loop you use. The difference lies in when the loop's counter (like i++) gets updated.
The Reliable For Loop
In a for loop, the update expression (the third part of the header) is guaranteed to run even if you trigger a continue.
#include <stdio.h>
int main() {
// This loop prints 0, 1, 2, 4 (skips 3)
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // Jumps straight to i++
}
printf("%d ", i);
}
return 0;
}
Even though we skipped the printf, the loop still performed i++ before checking the condition again. The loop progresses naturally.
The Infinite While Loop Trap
In a while loop, you usually put your update (i++) at the bottom of the code block. If a continue statement sits above that update, the program will jump back to the top of the loop before the counter ever changes.
int i = 0;
while (i < 5) {
if (i == 3) {
continue; // Jumps to (i < 5)
}
printf("%d ", i);
i++; // This is skipped forever if i is 3!
}
In this scenario, once i becomes 3, the continue triggers. The program jumps to the top, sees that 3 < 5 is true, hits the continue again, and repeats forever. Your program is now stuck in an infinite loop because the counter "update" was part of the code that got skipped.
How to Stay Safe
When using continue inside a while loop, always ensure your counter is updated before the continue statement, or consider if a for loop is a safer tool for the job.
Key takeaway
A continue in a for loop still executes the update step, but in a while loop, it can skip the update and cause an infinite loop.