Recently someone asked me that what can be the usage of below kind of macro:

#define LOOP(X) \
do{ \
............. \
............. \
............. \
}while(0)

In the first sight, it seems that a do-while loop with ‘0’ in the while condition serves no purpose. Since the loop-body will run just one time, so it seems that it’s worthless to write this kind of code.

But this "do { ... } while(0)" structure lets you put a compound statement (i.e., nest arbitrary logic) where a single statement is expected, so it behaves just like a function call. (It's the only structure that does.)

Consider these two macros, and how they'd be inserted in the following statement:
#define LOOP(msg) if (SomeCondition()) DoReport(msg)
and

#define LOOP(msg) do { if (SomeCondition()) DoReport(msg); } while (0)
...
if (OtherCondition())
LOOP("problem");
else
DoSomethingElse();
...

Note how the first one changes the logic at the insertion point. Effectively, it will become following:
...
if (OtherCondition())
if (SomeCondition())
DoReport(msg)
else
DoSomethingElse();
...
So we saw that this kind of macro is used when we want to save our macro from some kind of code developed in above manner.
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.