do ... while(0) in macros

Peter Barada pbarada at mail.wm.sps.mot.com
Wed Aug 8 14:31:36 UTC 2001


>This explanation is dead on the money.  If you define
>more than a single statement in a macro, it is a 
>good habit to get into.  It is a good way to avoid 
>bizarre and hard to debug problems like the one
>Paul is describing.

You're really close.  The reason that the do{ ... }while(0) was
chosen is that it allows you to invoke macors as if they are
functions(including the trailing semicolon) and get the correct
semantic action in all contructs, including the then clause of an
if/else statement.  As an example:

#define FOO(x) { printf("x is %d\n", x); exit(-1); }

void bar(int x)
{
  if (x)
    FOO(x);
}


would fine, but if we add an else clause:

#define FOO(x) { printf("x is %d\n", x); exit(-1); }

void bar(int x)
{
  if (x)
    FOO(x);
  else
    mumbleFratz();
}

Then the compiler barfs with:

test.c: In function `bar':
test.c:7: parse error before `else'

because the else is unexpected since the semicolon after the closing
brace terminates the if statement.  If the macro is defined using do{
... }while(0) then the semicolon is attached to the while statement,
and a trailing else is parsed correctly.

-- 
Peter Barada                                   Peter.Barada at motorola.com
Wizard                                         781-852-2768 (direct)
WaveMark Solutions(wholly owned by Motorola)   781-270-0193 (fax)



More information about the users mailing list