Reputation: 154818
When you use
continue
without a label, it terminates the current iteration of the innermost enclosingwhile
,do-while
orfor
statement and continues execution of the loop with the next iteration.
I'm not sure why the following piece of code does not work as I expect.
do {
continue;
} while(false);
Even though the while
condition is false
, I expect it to run forever since continue
jumps towards the start of the block, which immediately executes continue
again, etc. Somehow however, the loop terminates after one iteration. It looks like continue
is ignored.
How does continue
in a do-while
loop work?
Upvotes: 20
Views: 13461
Reputation: 47471
while(true)
to get an infinite loop.If you replaced while(false)
with while(true)
, you would get an infinite loop.
do {
continue;
} while(true);
continue
skips to the end of the block, which in a do-while loop, will execute the conditional statement.
In your case, your condition was false and therefore it terminates the loop. If that condition is true
, it would continue at the start of the loop.
Upvotes: 1
Reputation: 700242
I expect it to run forever since continue jumps towards the start of the block
The continue
doesn't jump to the start of the block, it jumps to the end of the block.
Upvotes: 4
Reputation: 3547
Check out this jsFiddle: http://jsfiddle.net/YdpJ2/3/
var getFalse = function() {
alert("Called getFalse!");
return false;
};
do {
continue;
alert("Past the continue? That's impossible.");
} while( getFalse() );
It appears to hit the continue, then break out of that iteration to run the check condition. Since the condition is false, it terminates.
Upvotes: 15
Reputation: 51797
continue
doesn't start over the current iteration again but skips to the next one (as said in the MDN-quote).
because of a false
condition, there is no next iteration - so the whole loop is completed.
Upvotes: 5
Reputation: 1887
continue
does not skip the check while(false)
but simply ignores the rest of the code within the brackets.
Upvotes: 13
Reputation: 1089
Continue stops execution of the rest of the code in the block and jumps directly to the next iteration of your loop.
Since you are doing while(false)
there is no next iteration
Upvotes: 5
Reputation: 14614
After the continue, the loop conditional is evaluated, since it is false, the loop will terminate.
Upvotes: 3