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 ; }
Enter fullscreen mode
Exit fullscreen mode
for.c…