_c language based on a macro definition containing if in C
Source: Internet
Author: User
Macro definition that contains if
When the macro definition contains an IF
1) define the following macros #define DC (P) if (foo (p)) fun (p)
Used in the following environment
if (k>n)
DC (k);
Else
DC (n);
After the macro is replaced, the following
if (k>n)
if (foo (k))
Fun (k);
Else
if (foo (n))
Fun (n);
Visible, the original if and else are no longer paired.
2 To avoid such problems, we can define a macro that contains an if statement as a whole. #define DC (P) {if (P)) fun (p);}
However, replace and then become
if (k>n)
{
if (foo (k))
Fun (k);
};else ...
If you have a semicolon in front of else, you are prompted at compile time that the error is not paired with else.
3 For these reasons, in the macro definition, the statement sequence is often placed in the do{...} while (0) block. As follows
#define DC (P) do{(if (foo (p)) fun (p); while (0)
After replacement
if (k>n)
Todo
{
if (foo (k))
Fun (k);
}while (0);
Else
...
Programs can run correctly
4) Replacement scheme A) adopted? : An expression #define DC (P) (foo (p))? (Fun (P)): 0)
( b) using the short path evaluation attribute of Boolean operation #define DC (P) ((foo (p)) && (Fun (p), 1)
Reference books: << code reading methods and practices >>
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.