Macro definition of if contained in C

Source: Internet
Author: User
Macro definition containing if

When the macro definition contains if
1) define the following macro
# Define DC (p) if (FOO (p) Fun (P)

Used in the following Environment
If (k> N)
DC (k );
Else
DC (N );

After macro replacement
If (k> N)
If (FOO (k ))
Fun (k );
Else
If (FOO (n ))
Fun (N );

It can be seen that the original if and else are no longer paired.

2) to avoid such problems, we can define the macro containing the if statement as a whole.
# Define DC (p) {If (FOO (p) Fun (p );}
However
If (k> N)
{
If (FOO (k ))
Fun (k );
}; Else...
Because there are multiple semicolons before else, an error will be prompted during compilation. If.

3) For these reasons, in macro definition, the statement sequence is often placed in do {...} while (0) block.
As follows:
# Define DC (p) do {(if (FOO (p) Fun (p);} while (0)
After replacement
If (k> N)
Do
{
If (FOO (k ))
Fun (k );
} While (0 );
Else
...
The program runs normally.

4) Replacement Scheme
A) use? : Expression
# Define DC (p) (FOO (p ))? (Fun (p): 0)

B) Evaluate the attribute using the short path of the Boolean operation
# Define DC (p) (FOO (p) & (fun (P), 1 ))

Reference books: <code reading methods and practices>



Related Article

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.