Do{...} The meaning and usage of while (0)

Source: Internet
Author: User

Reprint address: http://www.spongeliu.com/415.html Linux kernel and some other open source code, often encounter such code:
Do{...} while (0)

This code is not a loop at a glance, do. While the surface is meaningless here, why use it so much?

In fact, do{...} while (0) is much more useful than beautifying your code. Looked up some information, summed up this writing mainly has the following points of interest:

1, the auxiliary definition complex macro, avoids the reference error time:

For example, suppose you need to define a macro like this:

#define DoSomething ()               foo1 ();               Foo2 ();

The intent of this macro is that the function foo1 () and Foo2 () will be called when DoSomething () is called. But if you write this at the time of the call:

if (a>0)    dosomething ();

Because macros are directly expanded when they are preprocessed, you actually write the code like this:

if (a>0)    foo1 (); Foo2 ();

This causes a problem because the program is executed regardless of whether a is greater than 0,foo2 (), resulting in an error.

So just use {} to wrap foo1 () and Foo2 () together, okay?

When we write code, we are used to add a semicolon to the right of the statement, and if you use {} In a macro, the code is equivalent to this: "{...};", as it unfolds:

if (a>0) {    foo1 ();    Foo2 ();};

This will not even compile through. So, a lot of people have adopted do{...} while (0);

#define DoSomething ()         do{           foo1 ();          Foo2 ();        } while (0)    ... if (a>0)    dosomething ();

This way, the initial semantics are preserved only after the macro is expanded. GCC provides statement-expressions to replace do{...} while (0); So you can also define macros like this:

#define DoSomething () ({        foo1 ();         Foo2 (); })

Do{...} The meaning and usage of while (0)

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.