do{}while(flase)的用处

3 篇文章 0 订阅

之前工作的时候,看底层嵌入式代码,就看到过这种用法,当时没有深究,也没多想,今天又遇到这种用法,网上找了找,对这种使用方法进行一下总结。

一、 代替goto,goto可读性不好,好多公司不让用goto,故do{}while(false)代替

1. 相应的goto用法


if(condition1)
goto label;
if(condition2)
goto label;
....
return;
label:
........
2. 相应的do{}while(false)用法
do{
if(condition1)
break;
if(condition2)
break;
.....
return;
}while(FALSE);
...


二、代码分分块,类似 {}

bool CCLayer::init()
{
bool bRet = false;

    do 
    {        
        CCDirector * pDirector;
        CC_BREAK_IF(!(pDirector = CCDirector::sharedDirector()));
        this->setContentSize(pDirector->getWinSize());
        m_bTouchEnabled = false;
        m_bAccelerometerEnabled = false;
        // success
        bRet = true;
} while(0);

    return bRet;
}


三、 代替多层判断,嵌套操作

if(!condition1)
  if (!condition2)
    {return;}  

do{  
if(condition1){  
printf("condition1!");  
break;  
} if(condition2){  
printf("condition2!");  
 break;  
}.....  
return;  
}while(FALSE);  
...  

四、 兼容编译器,有些编译器变量必须在语句块开始的时候声明

int a;
a = 10;
int b;
b = 20;

int a;
a = 10;
do
{
   int b;
   b = 20;
}while(0);


五、 为了宏展开的时候不会出错,Linux内核就用这些东西。

例1:a,b是两条语句

#define AB1    a; b;     // x, 下面语句b不能被执行: if (cond) AB1;
#define AB2    { a; b; }  // x, 下面语句编译出错:if (cond) AB2; else ...;
#define AB3    a, b      // x, 有运算符优先级问题
#define AB4    do { a; b; } while (0)
例2:

			#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分支后有两个statement,导致else分支没有对应的if语句,编译错误。  
			//2)if后边跟两个语句,没有大括号,第二个语句必然永远都能执行。  


六、代码中一个return,多处return代码过于混乱


if(...)
{
  do sth...
  if(...)
  {
    do sth...
    if(...)
    {
     do sth...
     }
    else
    {
      return -3;
    }
  }
}

int nRet = 0;
do
{
  if(!...)
  { 
    nRet = -1;
    break; 
  }
   do sth...
  if(!...)
  { break; }
  do sth...
  if(!...)
  { break; }
  do sth...
  nRet = 0;
}while(0);

return nRet;



引用:

http://www.cnblogs.com/zhuyf87/archive/2013/02/01/2889507.html

http://blog.csdn.net/huqinwei987/article/details/26290575




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值