What I mean is this :
while (i < 10) {
if (i == 4) {
// i++; should be here, but if I skip it...
continue;
}
cout << i << endl;
i++;
}
I am getting this :
1
2
3
and that’s it! It just stays like that, without termination… unless I specifically mention i++ before continue in the if block, I have this "problem".
Why do I have to specifically mention i++ ? Shouldn’t the continue statement just go to the next iteration ? Is this a feature and has no explanation, or is there something wrong with my code ?
Edit: Thanks to the comments for the answer! continue does indeed go to the next iteration, but since I did not increment it in the if block to change the outcome (from true to false) for the next time it goes through, the value of i stays 4 forever, thus becomes an infinite loop.
It is to be noted that it does not happen when using a for loop, because the syntax is different in the way that in a for loop, the i++ is given which doesn’t need to be mentioned specifically.
for (int i = 0; i < 10; i++) {
if (i == 4) {continue;}
cout << i << endl;
}
Here iteration is a part of the loop, hence I assume you wouldn’t run into the same problem when using a for loop.
>Solution :
Think about what the loop does:
It's 0! Lets print it and increment it. Lets go to the next iteration!
It's 1! Lets print it and increment it. Lets go to the next iteration!
It's 2! Lets print it and increment it. Lets go to the next iteration!
It's 3! Lets print it and increment it. Lets go to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
... (and infinitely so)
You need to increase i for it to skip the "4"