Do {} while (0) in the kernel)

Source: Internet
Author: User
Tags parse error

Why are there so many do {} while (0) Macros in the kernel? I don't understand it at first. It doesn't seem to work. But after understanding it, you will know its benefits. The benefit lies in the macros of multiple statements.

 
# Define Foo (x) print ("Arg is % Sn", x); do_something (X );

InCodeUsed in:

 
If (2 = blah) Foo (blah );

After pre-compilation is expanded:

 
If (2 = blah) print ("Arg is % Sn", blah); do_something (blah );

As you can see, the do_something function is out of the IF statement control. This is not what we want. Use do {} while (0); It is foolproof.

 If (2 = blah) do {printf ("Arg is % Sn", blah); do_something (blah);} while (0 ); of course, you can also use the following form: # define exch (x, y) {int TMP; TMP = x; X = y; y = TMP ;} however, it may cause problems in the IF-else statement. For example: 
 If (x> Y) exch (x, y); // branch 1elsedo_something (); // branch 2 

after expansion:

 If (x> Y) {// single-branch if-statement !!! Int TMP; // The one and only branch consiststmp = x; // of the block. X = y; y = TMP; V}; // empty statementelse // Error !!! "Parse error before else" do_something (); 

the syntax is incorrect. If do {} while (0) is used, this problem will not occur.

 If (x> Y) do {int TMP; TMP = x; X = y; y = TMP;} while (0); elsedo_something (); 

Well, remember to use your own code after you understand it!

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.