更詳細參考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();