核心裡的do{}while(0)

來源:互聯網
上載者:User

為啥核心裡有這麼多 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 1elsedo_something();     // Branch 2

展開後:

if (x > y) {                // Single-branch if-statement!!! int tmp;            // The one and only branch consiststmp = 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);elsedo_something();

嗯,現在明白之後,自己的代碼也記得用啊! 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.