更详细参考Kernelnewbies
为啥内核里有这么多 do{ }while(0) 的宏啊?一开始我也好不明白。感觉不出用了会有什么效果。不过明白之后就知道它的好处了。好处就在于多语句的宏。
#define FOO(x) print("arg is %sn",x);do_something(x);
在代码中使用:
if(2==blah) FOO(blah);
预编译展开后:
if(2==blah) print("arg is %sn",blah); do_something(blah);
看到了吧,do_something函数已经脱离了if语句的控制了。这可不是我们想要的。使用do{}while(0);就万无一失了。
if (2== blah) do { printf("arg is %sn", blah); do_something(blah); } while (0); 当然你也可以使用下面这种形式: #define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; } 但是它在if-else语句中会出现问题。如: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;v}; // empty statementelse // ERROR!!! "parse error before else"do_something();看到了吧,else成了语法错误了。使用do{}while(0)就不会有这个问题了。
if (x > y) do { int tmp; tmp = x; x = y; y = tmp; } while(0); else do_something();