do { ... } while (0) — what is it good for? [duplicate] do { ... } while (0) — what is it good for? [duplicate] c c

do { ... } while (0) — what is it good for? [duplicate]


It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)if (condition)    FOO(x);else // syntax error here    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)    FOO(x)else    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)    FOO(x);else    ....


It is a way to simplify error checking and avoid deep nested if's. For example:

do {  // do something  if (error) {    break;  }  // do something else  if (error) {    break;  }  // etc..} while (0);


It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {  if (n)     FOO(n);}

then this expands to:

void foobar(int n) {  if (n)     foo(n);bar(n);}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.