do...while(0)的作用

本文详细介绍了如何通过消除冗余代码、避免使用goto语句以及优化宏定义来提高代码质量。包括利用do...while(0)替代goto语句避免编译错误、避免空语句导致的编译警告,并提供了gcc编译器的替代方法。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值