4

Possible Duplicate:
how does do{} while(0) work in macro?

Example from this blog post:

#define VTAILQ_INSERT_BEFORE(listelm, elm, field) do {              \
    (elm)->field.vtqe_prev = (listelm)->field.vtqe_prev;            \
    VTAILQ_NEXT((elm), field) = (listelm);                          \
    *(listelm)->field.vtqe_prev = (elm);                            \
    (listelm)->field.vtqe_prev = &VTAILQ_NEXT((elm), field);        \
} while (0)

I've come across others, but this one highlights what I mean well enough

Community
  • 1
  • 1
TheIronKnuckle
  • 7,224
  • 4
  • 33
  • 56

1 Answers1

7

Long story short:

If you use a non looped macro in an unbraced if else statement, you will get screwed.

if (a)
    VTAILQ_INSERT_BEFORE(c, d, e);
else
    blah(b);

Would break terribly in this case.

More detailed answer here:

Why use apparently meaningless do-while and if-else statements in macros?

Community
  • 1
  • 1
Brett McLain
  • 2,000
  • 2
  • 14
  • 32