Do {... } While (0)

Source: Internet
Author: User
Tags define local

Why do I encounter many # defines... do {...} while (0) in the kernel )?

There are several reasons:

· Empty statements will be warned during compilation, so it is necessary to use # define Foo do {} while (0 ).

· This is done to define local variables in it

· This is to be able to use complex macro definitions in conditional statements. For example, the following code:

# Define Foo (x )\

Printf ("Arg is % s \ n", x );\

Do_something_useful (X );

If the following code is used:

If (blah = 2)

Foo (blah );

Will be expanded:

If (blah = 2)

Printf ("Arg is % s \ n", blah );

Do_something_useful (blah );;

In this way, the IF condition contains the printf () statement, while the do_something_useful () call cannot work as expected. When do {...} while (0) is defined, the following statement is displayed:

If (blah = 2)

Do {

Printf ("Arg is % s \ n", blah );

Do_something_useful (blah );

} While (0 );

This is the expected situation.

· If you want to define a multi-line statement and some local variables, the general definition can only be as follows:

# Define exch (x, y) {int TMP; TMP = x; X = y; y = TMP ;}

However, in some cases, this does not work normally. The following is an if statement that contains two branches:

If (x> Y)

Exch (x, y); // branch 1

Else

Do_something (); // branch 2

However, this can only be expanded into an if statement with a single branch, as shown below:

If (x> Y) {// single branch if

Int TMP;

TMP = X;

X = y;

Y = TMP;

}

; // Empty statement

Else // Error !!! "Parse error before else"

Do_something ();

The problem is caused by adding a semicolon (;) directly after the statement block. the solution is to place the statement block in the middle of DO and while (0. in this way, a single statement is obtained, instead of being judged as a statement block by the compiler. the IF statement is as follows:

If (x> Y)

Do {

Int TMP;

TMP = X;

X = y;

Y = TMP;

} While (0 );

Else

Do_something ();

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.