#define XXX do{XXX} while (0) Why this usage
Often encounter a very "strange macro definition", Rt. (Osiba ... Don't think deep enough, whip, clap
Recently met this guy, Quora above love God answered this question, I also worship
Http://www.quora.com/What-is-the-purpose-of-using-do-while-0-in-macros
This is the C language inside the macro definition, no ambiguity or side effects of a common technique.
Consider the situation.
#define FOO (x) bar (x); Baz (x)
Foo (wolf);
in general, expand to the following code:
Bar (Wolf); Baz (Wolf);
It's all right, no problem. But if you encounter an if judgment statement, take a look at the following example.
F (!feral) foo (Wolf);
This expands into the following form, (⊙o⊙) See, is there a situation where you do not want the thick line to pinch?
Here the IF statement can only be used for the first bar () function and cannot be used for the second Baz (). But this approach is probably not the programmer's intention.
The original idea is to make the Foo list as a whole.
if (!feral) bar (Wolf); Baz (Wolf);
Equivalent to the following form
if (!feral) bar (Wolf); Baz (Wolf);
left thedo/while (0) You don't want to play the macro definition like a function.
If you use this technique to define a macro definition,
#define FOO (x) do {bar (x), Baz (x);} while (0)
Or this macro definition, so use
F (!feral) foo (Wolf);
It becomes the following form.
if (!feral) do {bar (Wolf), Baz (Wolf);} while (0);
equivalent to
if (!feral) { bar (wolf); Baz (Wolf);
You might think, in this way, adding a {} doesn't solve the problem? Why do you want to do{} while (0)?
consider the following situation
#define FOO (x) {bar (x); Baz (x);}
if (!feral) foo (wolf); else bin (Wolf);
this becomes the
if (!feral) { bar (wolf); Baz (Wolf);}; else bin (Wolf);
Note that this makes the else the "infamous" dangling else.
#define XXX do{XXX} while (0) Why this usage