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))
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.