regex4html
regex4html

Reputation: 457

How to write this loop better?

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.

Upvotes: 17

Views: 763

Answers (6)

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

A possibile solution is this

for( ; doorIsLocked(); knockDoor() )

but you can also try this

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

Upvotes: 0

polygenelubricants
polygenelubricants

Reputation: 383866

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


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

Related questions

Upvotes: 43

Nordic Mainframe
Nordic Mainframe

Reputation: 28757

Here you are:

while(knockOnDoor(),doorIsLocked());

Upvotes: 5

Orochi
Orochi

Reputation: 397

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();

Upvotes: 0

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248129

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

Upvotes: 3

wheaties
wheaties

Reputation: 35980

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

Upvotes: 1

Related Questions