1

Possible Duplicates:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
What's the use of do while(0) when we define a macro?

Is there a difference between

#define MACRO(x)  \
    {             \
    ...           \
    }         

and

#define MACRO(x)   \
    do {           \
    ...            \
    } while(0)        

?

Community
  • 1
  • 1
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141

3 Answers3

1

Well, the second feels more natural since it always requires a semicolon after using it.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

do { ... } while(0) allows the macro to be used in conditional code.

Looks like this question has been asked before: C multi-line macro: do/while(0) vs scope block

Here's another link to a couple of reasons to do so, and why to omit the semicolon at the end.

Community
  • 1
  • 1
Nicolas Kaiser
  • 1,628
  • 2
  • 14
  • 26
0

EDIT RE-EDITED

in literature I can remember always the form do {..} while(0) (sometimes even with the ;, but this form proved to be wrong). Since macros are literal substitution, it is easy to imagine that there's a difference when { } is allowed but do { } while(0) is not, or when you need the MACRO behaves like a "statement" ({ }; do not, while do { } while(0); does; an example is the case of if / else( if):

   if (COND)
   {          // MACRO(..);         
      ...  
   };
   else
   {      // this is an else without if
   }

while

   if (COND)
     do {        // MACRO(..);
      ...
     } while(0);
   else
   {
     // this work properly
   }

So the first has a void statement that syntactically makes impossible to "join" the else to its if, while the second form is correct (and if the macro has the final ; as I remembered to have seen somewhere, the same error of the first form occurs)

ShinTakezou
  • 9,432
  • 1
  • 29
  • 39