Wondering what a continue
statement does in a do...while(false)
loop, I mocked up a simple test-case (pseudo-code):
count = 0;
do {
output(count);
count++;
if (count < 10)
continue;
}while (false);
output('out of loop');
The output was, to my surprise:
0
out of loop
A bit confused, I changed the loop from a do...while
to a for
:
for (count = 0; count == 0; count++) {
output(count);
if (count < 10)
continue;
}
output('out of loop');
While functionally not the same, the purpose is practically the same: Make a condition only satisfied the first iteration, and in next ones continue (until a certain value is reached, purely for stopping possible infinite-loops.) They might not run the same amount of times, but functionality here isn't the important bit.
The output was the same as before:
0
out of loop
Now, put into terms of a simple while
loop:
count = 0;
while (count == 0) {
output(count);
count++;
if (count < 10)
continue;
}
output('out of loop');
Once again, same output.
This is a bit confusing, as I've always thought of the continue
statement as "jump to the next iteration". So, here I ask: What does a continue
statement do in each of these loops? Does it just jump to the condition?
((For what it's worth, I tested the above in JavaScript, but I believe it's language-agnostic...js had to get at least that right))
A continue statement ends the current iteration of a loop. Program control is passed from the continue statement to the end of the loop body. A continue statement has the form: 1 continue ; A continue statement can only appear within the body of an iterative statement, such as do , for , or while .
The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.
The continue statement passes control to the next iteration of the nearest enclosing do , for , or while statement in which it appears, bypassing any remaining statements in the do , for , or while statement body.
Continue is also a loop control statement just like the break statement. continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggest the continue statement forces the loop to continue or execute the next iteration.
In a for loop, continue runs the 3rd expression of the for statement (usually used as some kind of iteration), then the condition (2nd expression), and then the loop if the condition is true. It does not run the rest of the current iteration of the loop.
In a while (or do-while) loop, it just runs the condition and then the loop if the condition holds. It also does not run the rest of the current iteration of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With