Skip to main content

Trivial do-while loop

Posted in

You might have seen such code.

do {
// ...
} while (0);

Me personally have seen it a lot and never knew what was this for.

There 2 reasons for doing this:

  • Multiline macros
  • Cleaning up

Multiline macros

There is nothing wrong with using backslashes when defining a macro. The problem comes when you try to use this macro, let's say, in an if statement.

#define MACRO() \
    f1(); \
    f2();
 
//...
 
if (some_cond)
    MACRO();
else
    // do something else

Oops... I don't think this code compiles, but even if it does it definitely doesn't do what you expect.
Only f1() will be called, but I bet you expect f1() and f2() to be called when some_cond occurs

The first thing that comes to mind is to use braces. But the thing is that the compiler may omit them due to optimization. In this case the trivial do-while loop will help us.

#define MACRO() \
    do { \
        f1(); \
        f2(); \
    } while (0)
 
//...
 
if (some_cond)
    // everything is ok here now...
    MACRO();
else
    // do something else

Cleaning up

In your initialization routine the trivial do-while loop can help you do some cleaning.

do {
    // declare vars needed for initialization routine
    doInitRoutine();
} while (0);
 
// vars needed for initialization are gone,
// since they are not needed at this point already.

To be continued...

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 o.     O                            o              
Oo o oO O
O O O O O
O o o o o
O o O .oOoO' O 'o O OoOo. 'o O
o O O O o o O o o O o O o o
o Oo o O O o O O o O o O O
O `o `OoOo OooOO `Oo'oO' `OoO' `Oo'oO'
O
`o
Enter the code depicted in ASCII art style.