Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using continue in a do-while loop

MDN states:

When you use continue without a label, it terminates the current iteration of the innermost enclosing while, do-while or for 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?

like image 359
pimvdb Avatar asked Jun 30 '12 13:06

pimvdb


People also ask

Can you use continue in a Do While loop?

Short answer yes, continue (and break) work properly in do while loops.

Can we use continue in do while loop in C?

For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do... while loops, continue statement causes the program control to pass to the conditional tests.

What is the Continue statement in a while loop?

The continue statement gives you the option to skip over the part of a loop where an external condition is triggered, but to go on to complete the rest of the loop. That is, the current iteration of the loop will be disrupted, but the program will return to the top of the loop.

Does continue work in while loop Java?

Continue statement in java can be used with for , while and do-while loop.


1 Answers

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.

like image 113
Kevin McKelvin Avatar answered Sep 22 '22 23:09

Kevin McKelvin