开发者

How to write this loop better?

I have a code that does something like this:

开发者_如何学JAVAwhile (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-while instead of a while-do loop:

do {

  knockOnDoor();

} while (doorIsLocked());

openDoor();

Unlike a while-do loop, the do-while executes the body once before checking the termination condition.

See also

  • Wikipedia/Do while loop

Pre-test and post-test loops

The do-while loop -- sometimes called just a do statement -- 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 loops while a condition is true, terminating immediately once it's false.

Pascal has a repeat-until loop, which is also a "post-test" loop; it loops while a condition is false, terminating immediately once it's true.

Fortran's do-while loop 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-do and for loops are also "pre-test" loops.

Always check language reference when in doubt.

References

  • MSDN: C++ Language Reference: The do-while Statement
  • MSDN: C# Language Reference: do
  • Java Language Specification §14.13: The do Statement

Related questions

  • Test loops at the top or bottom? (while vs. do while)
  • Is there ever a need for a do {…} while ( ) loop?
  • When is a do-while appropriate?


Here you are:

while(knockOnDoor(),doorIsLocked());


@polygenelubricants already posted the obvious best solution to this.

In some cases though, it may be simpler to remove the condition from the loop entirely, and do something like this:

for (;;) {
  knockOnDoor();
  if (!doorIsLocked()) { break; }
}

since it gives you full control over what to do before and after the loop condition.

But when a do-while does what you need, definitely prefer that.


You could do a recursive call:

void openLockedDoor(){
    knockOnDoor();
    if( doorIsLocked() ){
        return openLockedDoor();
    }
    return openDoor();
}

but the do-while above works just as well (or even better depending on your compiler.)


You forgot to Wait...If you keep on knocking it would also be impolite...so best way is to do it like this:

#define WAITING_TIME 2000 //2 Seconds are enough waiting time for another knock
while(doorIsLocked()){
knockOnDoor();
//Now wait
Sleep(WAITING_TIME);
}
openDoor();


A possibile solution is this

for( ; doorIsLocked(); knockDoor() )

but you can also try this

for( ; doorIsLocked();  ){
    knockDoor();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜