#define XXX do{XXX} while (0) Why this usage

Source: Internet
Author: User

#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

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.