do while 的兩個小技巧

來源:互聯網
上載者:User

 do {
...
}
while (0); // while (false)
的一點有用的小技巧:

1. 在宏裡用:


看下面情況:
#define swap(x,y) { int tmp = x; x = y; y = tmp; }
使用時如果這樣寫:
if (condition) swap(a, b);

else {...}
將被替換成:if (condition) {int tmp = x; x = y; y = tmp; } ;

else { ... }
這樣就會產生編譯錯誤(if字句裡的花括弧後面多了分號)。避免出現這樣問題的方法:
#define swap(x,y) do { int tmp = x; x = y; y = tmp; } while (0)

2. 替代goto語句:


goto語句破壞了程式的結構化,但是適當的使用恰到好處的goto語句有時非常有用,能少打很多代碼,如:
int *p = new int;
...
if (condition1) {
    delete p;      // 冗餘代碼

    return NULL;
}
else if (condition2) {
    delete p;      // 冗餘代碼

    return NULL;
}
else if ...
...

return p;
這樣,用goto
語句就能減少冗餘的代碼:
if (condition1) goto FAILURE
;
else if (condition2) goto FAILURE
;
else if ...
...
return p;
FAILURE:
delete p;
return NULL;

do ... while
也可以達到同樣效果,並且結構上更好:
int *p = new int;
...
do {
    if (condition1) break
;
    else if (condition2) break
;
    else if ...
    ...
    return p;

} while (0);
delete p;
return NULL;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.