Why is 'continue' statement ignoring the loop counter increment in 'while' loop, but not in 'for' loop?
Solution 1
Because continue
goes back to the start of the loop. With for
, the post-operation i++
is an integral part of the loop control and is executed before the loop body restarts.
With the while
, the i++
is just another statement in the body of the loop (no different to something like a = b
), skipped if you continue
before you reach it.
Solution 2
The reason is because the continue
statement will short-circuit the statements that follow it in the loop body. Since the way you wrote the while
loop has the increment statement following the continue
statement, it gets short-circuited. You can solve this by changing your while
loop.
A lot of text books claim that:
for (i = 0; i < N; ++i) {
/*...*/
}
is equivalent to:
i = 0;
while (i < N) {
/*...*/
++i;
}
But, in reality, it is really like:
j = 0;
while ((i = j++) < N) {
/*...*/
}
Or, to be a little more pedantic:
i = 0;
if (i < 10) do {
/*...*/
} while (++i, (i < 10));
These are more equivalent, since now if the body of the while
has a continue
, the increment still occurs, just like in a for
. The latter alternative only executes the increment after the iteration has completed, just like for
(the former executes the increment before the iteration, deferring to save it in i
until after the iteration).
Solution 3
Your increment of i
is after continue, so it never gets executed
while(i<10) //causes infinite loop
{
.........
continue
i++
......
}
Solution 4
In any loop, continue moves execution back to the top of the loop, not executing any other instructions after the continue statement.
In this case, the for loop's definition is always executed (per standard C), whereas the i++; statement is NOT executed, because it comes AFTER the continue statement.
Thokchom
Bear with me, I am a slow learner, but I am sincere and really interested to learn programming.
Updated on July 09, 2022Comments
-
Thokchom almost 2 years
Why does it tend to get into an infinite loop if I use
continue
in awhile
loop, but works fine in afor
loop?
The loop-counter incrementi++
gets ignored inwhile
loop if I use it aftercontinue
, but it works if it is infor
loop.If
continue
ignores subsequent statements, then why doesn't it ignore the third statement of thefor
loop then, which contains the counter incrementi++
? Isn't the third statement offor
loop subsequent tocontinue
as well and should be ignored, given the third statement offor
loop is executed after the loop body?while(i<10) //causes infinite loop { ... continue i++ ... } for(i=0;i<10;i++) //works fine and exits after 10 iterations { ... continue ... }