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?
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.
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.
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.
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).
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With