Monday 10 March 2014

What is the meaning of do{...} while(0)

    Sometimes we see some codes in C using this pattern: do{...} while(0). It looks it doesn't do anything else but just simply running everything in the braces. When I saw these codes the first time, I also felt weird. Then I did some research and post it. I hope it can help you.

    This pattern is only used in C or C++’s conditional compilation and when you want to use #define to represent multiple statements. A simple sample is like this:

#define function(x)  do { a(x); b(x); }while (0)

so, we can use it like this:

if(some condition){
    function(x);
}

else 
      blah blah....

     Why we have to use this pattern? When you want to use #define to represent multiple statements, 
this statement wouldn't work:
#define function(x)  foo(x); bar(x)   //cause syntax error in the if statement

this statement still won't work:
#define FOO(x) { foo(x); bar(x); } // doesn't work
 
only in this pattern:
#define function(x)  do { a(x); b(x); }while (0)
It work well in the if statement.

That is my study about this thing. I hope I can help you.

Hua

No comments:

Post a Comment