|
楼主 |
发表于 2006-9-12 13:33:48
|
显示全部楼层
搜了一下,发现竟然好多人问这个问题.看看别人的回答.
do {......} while(0)
A few days ago a came across a macro in the linux kernel code
#define MACRONAME do {Some code} while (0)now I was wondering what is the use of having while(0)
here's the explaination for it, by Ben Collins , on kernelnewbies
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 to:
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 would 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 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 would 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:
if(x>y)exch(x,y); // Branch 1elsedo_something(); // Branch 2But it would be interpreted as an if-statement with only one branch:
if(x>y) { // Single-branch if-statement!!!int tmp; // The one and only branch consiststmp = x; // of the block.x = y;y = tmp;}; // empty statementelse // 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);elsedo_something();
又看:http://www.everything2.com/index.pl?node_id=1180050
答的真好!!! |
|