do...while(0)的作用

1. 消除代码的冗余以及无需使用goto语句。

int* p = new int;
bool bOK(true);

do{
    bOK = func1();
    if(!bOK) break;
    bOK = func2();
    if(!bOK) break;
    //...
}while(0);
delete p;
p = NULL;
 

2. 宏定义中的do...while(0)避免悬空else分支导致编译失败或运行错误如:

#define safe_delete(p) do{ delete p; p = NULL;}while(0)
if (p != NULL)
  safe_delete(p);
else
  do...sth...

(1)如果去掉do...while(0)则会导致else无对应的if语句,导致编译错误。

(2)假设无else语句,则宏定义中的第二句将永远执行,导致意想不到的结果

3. 免去空语句出现编译告警。

In older compilers, this was necessary to prevent the compiler from issuing a warning. For example:

#define do_nothing do {} while (0)

The current gcc compiler provides another method that can be used in place of the do-loop idiom as shown in the following example.

#define foo ({

statement_1;

statement_2;

})

原文地址:https://www.cnblogs.com/eric-geoffrey/p/3163783.html