Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of a do-while(false)?

Tags:

When looking through some code that was handled by another employee, I see a lot of code written in:

do{     ... }while(false); 

What advantage (if any) does this provide?

Here is more of a skeleton that is happening in the code:

try{     do{         // Set some variables          for(...) {             if(...) break;             // Do some more stuff             if(...) break;             // Do some more stuff         }     }while(false); }catch(Exception e) {      // Exception handling  } 

Update:

C++ Version:
Are do-while-false loops common?

like image 692
Ascalonian Avatar asked Sep 18 '09 14:09

Ascalonian


People also ask

What are the advantages of do-while loop?

The advantage of a do... while loop is that it executes the block of code at least once , and then repeatedly executes the block depending on the condition.

What does while false do?

while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop. while (true) is covered by Tamra, while(false) could be used to temporarily skip the while loop when debugging code.

What happens when while loop is false?

With pretest loops such as the while loop, the program may never execute the loop statements. If the initial evaluation of the while statement's true/false expression is false, the program skips all statements of the loop and continues execution after the while statement.

When to use do-while instead of while?

Do-while loops can be useful when you know you want the code to run at least once (a while loop will not run at all if the condition it checks for is false beforehand, but a do-while loop will run once before it checks).


2 Answers

Maybe it was done to be able to jump out of the "loop" at any time, e.g:

do {     ...     if (somethingIsWrong) break;     //more code     ... } while(false); 

But as others have said, I wouldn't do it like this.

like image 94
M4N Avatar answered Nov 23 '22 01:11

M4N


In Java, there is no reason to do this.

In C, this is a common idiom when defining macros:

Consider:

#define macro1 doStuff(); doOtherStuff() #define macro2 do{ doStuff(); doOtherStuff(); } while( false )  if( something ) macro1; // only the first statement in macro1 is executed conditionally if( something ) macro2; // does what it looks like it does 

...but macros in C are evil and should be avoided if at all possible.

Does your coworker come from a C background?

like image 41
moonshadow Avatar answered Nov 23 '22 01:11

moonshadow