Do {...} while (0) in the Linux kernel code indicates general Linux technology-Linux programming and kernel information. For details, see the following. In kernelnewbies.org/faq/, say:
There are a couple of reasons:
(From Dave Miller) Empty statements give a warning from the compiler so this is why you see # define FOO do {} while (0 ).
(From Dave Miller) It gives you a basic block in which to declare local variables.
(From Ben Collins) It allows you to use more complex macros in conditional code. Imagine a macro of several lines of code like:
# Define FOO (x )\
Printf ("arg is % s \ n", x );\
Do_something_useful (x );
Now imagine using it like:
If (blah = 2)
FOO (blah );
This interprets:
If (blah = 2)
Printf ("arg is % s \ n", blah );
Do_something_useful (blah );;
As you can see, the if then only encompasses the printf (), and the do_something_useful () call is unconditional (not within the scope of the if), like you wanted it. so, by using a block like do {...} while (0), you wocould get this:
If (blah = 2)
Do {
Printf ("arg is % s \ n", blah );
Do_something_useful (blah );
} While (0 );
Which is exactly what you want.
(From Per Persson) As both Miller and Collins point out, you want a block statement so you can have several lines of code and declare local variables. but then the natural thing wocould be to just use for example:
# Define exch (x, y) {int tmp; tmp = x; x = y; y = tmp ;}
However that wouldn't work in some cases. The following code is meant to be an if-statement with two branches:
But it woshould be interpreted as an if-statement with only one branch:
If (x> y) {// Single-branch if-statement !!!
Int tmp; // The one and only branch consists
Tmp = x; // of the block.
X = y;
Y = tmp;
}
; // Empty statement
Else // ERROR !!! "Parse error before else"
Do_something ();
The problem is the semi-colon (coming directly after the block.
The solution for this is to sandwich the block between do and while (0 ). then we have a single statement with the capabilities of a block, but not considered as being a block statement by the compiler.
Our if-statement now becomes:
If (x> y)
Do {
Int tmp;
Tmp = x;
X = y;
Y = tmp;
} While (0 );
Else
Do_something ();
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