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>