Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the construct do .. while(false) contribute to better control flow?

I've recently come across this code:

do {
    if ( ! checkSomething() )
        break;

    // some code

    if ( ! checkSomeOtherThing() )
        break;

    // some other code
} while(false);

// some final code

The programmer that wrote it, wrote a comment along the lines of "cleaner control flow".

In my opinion, the original code could look better if its refactored into something else. But is there any truth in this statement ? Is this construct any good ?

like image 629
javs Avatar asked Apr 07 '26 02:04

javs


2 Answers

I find this much easier to read, and it produces an identical result:

if ( checkSomething() )
{
    // some code
    if ( checkSomeOtherThing() )
    {
        // some other code
    }
}
// some final code

I think do ... while is normally hard to follow, but using it for something other than a loop is misleading at best.

like image 60
robert Avatar answered Apr 10 '26 03:04

robert


This is equivalent to a goto.

In such situations, it is better to use a goto than to use an ugly hack.

Changing it to use a goto makes it much more readable:

if (!checkSomething())
    goto Done;

// some code

if (!checkSomeOtherThing())
    goto Done;

// some other code
Done: //some final code
like image 42
SLaks Avatar answered Apr 10 '26 02:04

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!