Based on the macro definition of if in C

  • 2020-04-02 00:54:46
  • OfStack

Contains the macro definition of if
When the macro definition contains an if
1) define the following macro
#define DC(p) if(foo(p))fun(p)
In the following context
If (k. > N)
DC (k);
The else
DC (n);
After the macro is replaced, the following appears
If (k. > N)
If (foo (k))
Fun (k);
The else
If (foo (n))
Fun (n);
So the original if and else don't match anymore.
2) to avoid this kind of problem, we can define macros containing if statements as a whole.
#define DC(p) {if(foo(p)) fun(p); }
But, instead, it becomes
If (k. > N)
{
If (foo (k))
Fun (k);
}; The else...
Because the else is preceded by a semicolon, there is an error at compile time that there is no if paired with the else.
3) for these reasons, in the macro definition, the statement sequence is often put into do{... } while (0) block.
The following
Define DC(p) do{(if(foo(p)) fun(p); } while (0)
After the replacement
If (k. > N)
The do
{
If (foo (k))
Fun (k);
} while (0);
The else
.
The program works fine
4) alternative plan
A) use? Expression:
Define DC(p) (foo(p)), right? (p) (fun) : 0)
B) use the short path evaluation attribute of Boolean operation
#define DC(p) ((foo(p)) && (fun(p), 1))
Reference books: < < Code reading methods and practices > >

Related articles: