I was writing a small parser logic in C++.
I previously wrote it in another language, so I knew it before hand.
Wrote the code, looking good, confident that it will run correctly.
But, it didn't! It skipped 2 tokens in a branch per iteration.
Why?
I started debugging, it was almost same to the original logic.
After careful observation, the only thing that I changed from the previous parser code was while loops.
Yep, just changed while loops to for loops.
I wanted to make the logic simple using a for loop and it broke the whole thing!
How?
In beginner online tutorials we learn that for loop is just a while loop with initialization, condition, and increment/decrement in one place.
But, its not!
Suppose, you got these 2 programs, one with a while loop and another with a for loop:
-
while.c:
#include<stdio.h>
int main(void){
int x = 0;
while(x < 10){
printf("%d\n",x);
if(x == 9){
continue;
}
x +=1;
}
return 0;
}
-
for.c:
#include<stdio.h>
int main(void){
for(int x = 0; x < 10; x +=1){
printf("%d\n",x);
if(x == 9){
continue;
}
}
return 0;
}
Both look same, but the output is different when we compile them:
- while.c output: It prints 1 2 3 4 5 6 7 8 9 and then keeps printing 9 forever.
- for.c output: It prints 1 2 3 4 5 6 7 8 9 and stops.
So, why it is different?
The thing is in while loop, the increment of x is not attached to the loop, so we decide if we want to increment or not.
Every iteration will end with the x incremented, but inside the if condition, we say continue, that is, without incrementing the x go to the next iteration.
But, in a for loop,
for (initialization; condition; iteration) {
// loop body
}
In the iteration clause or section of the for loop, what ever we put like for this case increment x, is run at the end of every iteration even when we use the keyword continue.
What happened in our code?
In the while loop when x is equal to 9 it does not increment the x and skips to next iteration, so it keeps printing the 9 and never get bigger than 9 so always less than 10.
In the for loop when x is equal to 9 it increments the x to 10 before continuing that is skipping to the next iteration.
So, it prints 0 to 9 and then the for loop condition is not satisfied, that is, should be less than 10 but its 10 so it stops.
Bottom-line
In while loop when you use continue, it will not do anything extra.It just skips to next iteration!
In for loop when you use continue ,it will run the iteration clause, that is, increments the counter and then runs the continue.
So, be careful!
Top comments (2)
🙀
Thanks 😄✨