I have a code that does something like this:
while (doorIsLocked()) {
knockOnDoor();
}
openDoor();
but I want to be polite and always knock on the door before I open it.
I can write something like this:
knockOnDoor();
while (doorIsLocked()) {
knockOnDoor();
}
openDoor();
but I’m just wondering if there’s a better idiom that doesn’t repeat a statement.
You can use a
do-whileinstead of awhile-doloop:Unlike a
while-doloop, thedo-whileexecutes the body once before checking the termination condition.See also
Pre-test and post-test loops
The
do-whileloop — sometimes called just adostatement — in C/C++/C#/Java/some others is what is known as a “post-test” loop: the terminating condition is checked after each iteration. It loopswhilea condition istrue, terminating immediately once it’sfalse.Pascal has a
repeat-untilloop, which is also a “post-test” loop; it loops while a condition isfalse, terminating immediately once it’strue.Fortran’s
do-whileloop on the other hand is a “pre-test” loop: the terminating condition is checked before each iteration. In C/C++/Java/C#/some others,while-doandforloops are also “pre-test” loops.Always check language reference when in doubt.
References
do-whileStatementdodoStatementRelated questions
whilevs.do while)do {…} while ( )loop?do-whileappropriate?