Why does it tend to get into an infinite loop if I use continue
in a while
loop, but works fine in a for
loop?
The loop-counter increment i++
gets ignored in while
loop if I use it after continue
, but it works if it is in for
loop.
If continue
ignores subsequent statements, then why doesn't it ignore the third statement of the for
loop then, which contains the counter increment i++
? Isn't the third statement of for
loop subsequent to continue
as well and should be ignored, given the third statement of for
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
...
}
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.