do { ... } while (0) — what is it good for?
Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)
Is it good for anything else? Do you use it?
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 grouping 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.
链接地址: http://www.djcxy.com/p/84408.html