What's the use of do while(0) when we define a macro? [duplicate]

ghz 1years ago ⋅ 6020 views

Question

This question already has answers here :

Closed 10 years ago.

The community reviewed whether to reopen this question 4 months ago and left it closed:

Original close reason(s) were not resolved

Possible Duplicates:
[Do-While and if-else statements in C/C++ macros](https://stackoverflow.com/questions/154136/do-while-and-if-else- statements-in-c-c-macros)
[do { … } while (0) — what is it good for?](https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good- for)

I'm reading the linux kernel and I found many macros like this:

#define INIT_LIST_HEAD(ptr) do { \
    (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)

Why do they use this rather than define it simply in a {}?


Answer

You can follow it with a semicolon and make it look and act more like a function. It also works with if/else clauses properly then.

Without the while(0), your code above would not work with

if (doit) 
   INIT_LIST_HEAD(x);
 else 
   displayError(x);

since the semicolon after the macro would "eat" the else clause, and the above wouldn't even compile.