# Define XXX do {XXX} while (0) Why is this usage,

Source: Internet
Author: User

# 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.







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.