# Define XXX do {XXX} while (0) Why is this usage,
# Define XXX do {XXX} while (0) Why is this usage
I often encounter a very "Strange macro definition", rt)
I recently met this guy again. Quora's Love God answered this question, so I would worship it.
Http://www.quora.com/What-is-the-purpose-of-using-do-while-0-in-macros
This is a common technique in C language that does not cause ambiguity or side effects.
Consider the situation
#define foo(x) bar(x); baz(x)
foo(wolf);
The general code is expanded to the following:
bar(wolf); baz(wolf);
This is okay, no problem. But if you encounter an if judgment statement, let's look at the example below.
f (!feral) foo(wolf);
This is extended into the following form. (⊙ o ⊙) See, is there a situation where you don't want to be rough?
Here, the if statement can only act on the first bar () function and cannot act on the second baz (). However, this method is probably not intended by the programmer.
The intention is to make the foo ticket a whole ~
if (!feral) bar(wolf); baz(wolf);
It is equivalent to the following format:
if (!feral) bar(wolf);baz(wolf);
If you leave do/while (0), you don't want to play the same macro definition as the function ~
If you use this technique to define macro definitions,
#define foo(x) do { bar(x); baz(x); } while (0)
This macro definition is used in this way.
f (!feral) foo(wolf);
It becomes the following form.
if (!feral) do { bar(wolf); baz(wolf); } while (0);
Equivalent
if (!feral) { bar(wolf); baz(wolf);}
You may think, in the following way, adding {} will not solve the problem? Why do we need do {} while (0 )?
Consider the following situations:
#define foo(x) { bar(x); baz(x); }
if (!feral) foo(wolf);else bin(wolf);
This becomes
if (!feral) { bar(wolf); baz(wolf);};else bin(wolf);
Note! This makes else a "Notorious" dangling else.