1

Possible Duplicate:
What's the use of do while(0) when we define a macro?

When I'm reading through Linux kernel code, the header files often have #define blocks that look like (from include/linux/wait.h in 2.6.37):

#define init_waitqueue_head(q)  \
    do {                        \
        ...                     \
    } while (0)

What is the purpose of the do...while sequence when the "loop" will only ever execute once? It makes sense that a programmer would want to open up a new scope for temporary variables, but that doesn't require the do...while to exist. Is it just syntactic sugar, or does it help the compiler in some way?

Similarly, I've seen lines of code with an if statement that looks like (from include/linux/kfifo.h):

#define kfifo_put(fifo, val) \
    ...                      \
    if (0) {                 \
        ...                  \
    }

Also in a #define, again why not just remove that tidbit instead of having it never run? I'll note that in the kfifo_put define the scoping is started with { and ends with } without a do...while loop.

Community
  • 1
  • 1
mjschultz
  • 1,936
  • 1
  • 18
  • 20
  • See: [Why are there sometimes meaningless do-while and if-else statements in C macros?](http://stackoverflow.com/questions/154136/why-are-there-sometimes-meaningless-do-while-and-if-else-statements-in-c-c-macr) – hammar May 04 '11 at 15:48
  • 2
    The `if (0) { ... }`: these are still compiled and can throw compilation errors. In this case it's a compile-time check for some property of the types of the parameters passed. – Rup May 04 '11 at 15:50

0 Answers0