分类: C/C++
2009-02-03 19:50:12
为什么很多linux内核中宏#defines用do { ... } while(0)?
有很多原因:
(Dave Miller的说法):
编译器对于空语句会给出告警,这是为什么#define FOO do{ }while(0);
给定一个基本块(局部可视域),定义很多局部变量;
(Ben Collins的说法):
在条件代码中,允许定义复杂的宏。可以想像有很多行宏,如下代码:
#define FOO(x) \现在,想像下面的应用:
printf("arg is %s\n", x); \
do_something_useful(x);
if (blah == 2)展开后代码为:
FOO(blah);
if (blah == 2)
printf("arg is %s\n", blah);
do_something_useful(blah);;
if (blah == 2)
do {
printf("arg is %s\n", blah);
do_something_useful(blah);
} while (0);
#define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }
if (x > y)
exch(x,y); // Branch 1
else
do_something(); // Branch 2
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();
if (x > y)
do {
int tmp;
tmp = x;
x = y;
y = tmp;
} while(0);
else
do_something();
#define FOO(arg) ({ \
typeof(arg) lcl; \
lcl = bar(arg); \
lcl; \
})