Why do I encounter many # defines... do {...} while (0) in the kernel )?
There are several reasons:
· Empty statements will be warned during compilation, so it is necessary to use # define Foo do {} while (0 ).
· This is done to define local variables in it
· This is to be able to use complex macro definitions in conditional statements. For example, the following code:
# Define Foo (x )\
Printf ("Arg is % s \ n", x );\
Do_something_useful (X );
If the following code is used:
If (blah = 2)
Foo (blah );
Will be expanded:
If (blah = 2)
Printf ("Arg is % s \ n", blah );
Do_something_useful (blah );;
In this way, the IF condition contains the printf () statement, while the do_something_useful () call cannot work as expected. When do {...} while (0) is defined, the following statement is displayed:
If (blah = 2)
Do {
Printf ("Arg is % s \ n", blah );
Do_something_useful (blah );
} While (0 );
This is the expected situation.
· If you want to define a multi-line statement and some local variables, the general definition can only be as follows:
# Define exch (x, y) {int TMP; TMP = x; X = y; y = TMP ;}
However, in some cases, this does not work normally. The following is an if statement that contains two branches:
If (x> Y)
Exch (x, y); // branch 1
Else
Do_something (); // branch 2
However, this can only be expanded into an if statement with a single branch, as shown below:
If (x> Y) {// single branch if
Int TMP;
TMP = X;
X = y;
Y = TMP;
}
; // Empty statement
Else // Error !!! "Parse error before else"
Do_something ();
The problem is caused by adding a semicolon (;) directly after the statement block. the solution is to place the statement block in the middle of DO and while (0. in this way, a single statement is obtained, instead of being judged as a statement block by the compiler. the IF statement is as follows:
If (x> Y)
Do {
Int TMP;
TMP = X;
X = y;
Y = TMP;
} While (0 );
Else
Do_something ();