do..while(0)使用

在C中,有三種類型的循環語句:for, while, 和do...while, 但是在一般應用中作循環時, 我們可能用for和while要多一些,do...while相對不受重視。
    但是,最近在讀我們項目的代碼時,卻發現了do...while的一些十分聰明的用法,不是用來做循環,而是用作其他來提高代碼的健壯性。 
1. do...while(0)消除goto語句。
通常,如果在一個函數中開始要分配一些資源,然後在中途執行過程中如果遇到錯誤則退出函數,當然,退出前先釋放資源,我們的代碼可能是這樣:
version 1

bool Execute()
{
   // 分配資源
   int *p = new int;
   bool bOk(true);

   // 執行並進行錯誤處理
   bOk = func1();
   if(!bOk) 
   {
      delete p;   
      p = NULL;
      return false;
   }

   bOk = func2();
   if(!bOk) 
   {
      delete p;   
      p = NULL;
      return false;
   }

   bOk = func3();
   if(!bOk) 
   {
      delete p;   
      p = NULL;
      return false;
   }

   // ..........

   // 執行成功,釋放資源並返回
    delete p;   
    p = NULL;
    return true;
   
}



這裏一個最大的問題就是代碼的冗餘,而且我每增加一個操作,就需要做相應的錯誤處理,非常不靈活。於是我們想到了goto:
version 2

bool Execute()
{
   // 分配資源
   int *p = new int;
   bool bOk(true);

   // 執行並進行錯誤處理
   bOk = func1();
   if(!bOk) goto errorhandle;

   bOk = func2();
   if(!bOk) goto errorhandle;

   bOk = func3();
   if(!bOk) goto errorhandle;

   // ..........

   // 執行成功,釋放資源並返回
    delete p;   
    p = NULL;
    return true;
errorhandle:
    delete p;   
    p = NULL;
    return false;
   
}

代碼冗餘是消除了,但是我們引入了C++中身份比較微妙的goto語句,雖然正確的使用goto可以大大提高程序的靈活性與簡潔性,但太靈活的東西往往是很危險的,它會讓我們的程序捉摸不定,那麼怎麼才能避免使用goto語句,又能消除代碼冗餘呢,請看do...while(0)循環:
version3

bool Execute()
{
   // 分配資源
   int *p = new int;

   bool bOk(true);
   do
   {
      // 執行並進行錯誤處理
      bOk = func1();
      if(!bOk) break;

      bOk = func2();
      if(!bOk) break;

      bOk = func3();
      if(!bOk) break;

      // ..........

   }while(0);

    // 釋放資源
    delete p;   
    p = NULL;
    return bOk;
   
}
“漂亮!”, 看代碼就行了,啥都不用說了...
2 宏定義中的do...while(0)
  如果你是C++程序員,我有理由相信你用過,或者接觸過,至少聽說過MFC, 在MFC的afx.h文件裏面, 你會發現很多宏定義都是用了do...while(0)或do...while(false), 比如說:
#define AFXASSUME(cond)       do { bool __afx_condVal=!!(cond); ASSERT(__afx_condVal); __analysis_assume(__afx_condVal); } while(0) 
粗看我們就會覺得很奇怪,既然循環裏面只執行了一次,我要這個看似多餘的do...while(0)有什麼意義呢? 
當然有!
爲了看起來更清晰,這裏用一個簡單點的宏來演示:
#define SAFE_DELETE(p) do{ delete p; p = NULL} while(0)
假設這裏去掉do...while(0),
#define SAFE_DELETE(p) delete p; p = NULL;
那麼以下代碼:
if(NULL != p) SAFE_DELETE(p)
else   ...do sth...
就有兩個問題,
1) 因爲if分支後有兩個語句,else分支沒有對應的if,編譯失敗
2) 假設沒有else, SAFE_DELETE中的第二個語句無論if測試是否通過,會永遠執行。
你可能發現,爲了避免這兩個問題,我不一定要用這個令人費解的do...while,  我直接用{}括起來就可以了
#define SAFE_DELETE(p) { delete p; p = NULL;}
的確,這樣的話上面的問題是不存在了,但是我想對於C++程序員來講,在每個語句後面加分號是一種約定俗成的習慣,這樣的話,以下代碼:
if(NULL != p) SAFE_DELETE(p);
else   ...do sth...
其else分支就無法通過編譯了(原因同上),所以採用do...while(0)是做好的選擇了。
也許你會說,我們代碼的習慣是在每個判斷後面加上{}, 就不會有這種問題了,也就不需要do...while了,如:
if(...) 
{
}
else
{
}
誠然,這是一個好的,應該提倡的編程習慣,但一般這樣的宏都是作爲library的一部分出現的,而對於一個library的作者,他所要做的就是讓其庫具有通用性,強壯性,因此他不能有任何對庫的使用者的假設,如其編碼規範,技術水平等。

FAQ FROM CSDN:

FAQ/DoWhile0

Why do a lot of #defines in the kernel use do { ... } while(0)?

There are a couple of reasons:

  • (from Dave Miller) Empty statements give a warning from the compiler so this is why you see #define FOO do { } while(0).

  • (from Dave Miller) It gives you a basic block in which to declare local variables.

  • (from Ben Collins) It allows you to use more complex macros in conditional code. Imagine a macro of several lines of code like:

    #define FOO(x) / printf("arg is %s/n", x); / do_something_useful(x);

    Now imagine using it like:

    if (blah == 2) FOO(blah);

    This interprets to:

    if (blah == 2) printf("arg is %s/n", blah); do_something_useful(blah);;

    As you can see, the if then only encompasses the printf(), and the do_something_useful() call is unconditional (not within the scope of the if), like you wanted it. So, by using a block likedo { ... } while(0), you would get this:

    if (blah == 2) do { printf("arg is %s/n", blah); do_something_useful(blah); } while (0);

    Which is exactly what you want.

  • (from Per Persson) As both Miller and Collins point out, you want a block statement so you can have several lines of code and declare local variables. But then the natural thing would be to just use for example:

    #define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }

    However that wouldn't work in some cases. The following code is meant to be an if-statement with two branches:

    if (x > y) exch(x,y); // Branch 1 else do_something(); // Branch 2

    But it would be interpreted as an if-statement with only one branch:

    if (x > y) { // Single-branch if-statement!!! int tmp; // The one and only branch consiststmp = x; // of the block. x = y; y = tmp; ; // empty statement else // ERROR!!! "parse error before else" do_something();

    The problem is the semi-colon (;) coming directly after the block. The solution for this is to sandwich the block between do and while (0). Then we have a single statement with the capabilities of a block, but not considered as being a block statement by the compiler. Our if-statement now becomes:

    if (x > y) do { int tmp; tmp = x; x = y; y = tmp; } while(0); else do_something();
[zz]http://wenku.baidu.com/view/fcf5ea4bc850ad02de804153.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章