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