使用do{ } while(0);

来源:互联网 发布:从零开始学mt4编程 编辑:程序博客网 时间:2024/03/28 19:15

 

_Api(){     do     {         //do something     }while(0);}

这样的写法有什么好处啊?

有时候只是为了代码分块,比仅仅使用{}更直观些。

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;}

变形的goto,有些公司不让用goto。

// goto case{  if(!a) goto done;  //do something here  if(!b) goto done;  //do another thing here  done:   //final step goes here}// do ... while(0){  do  {    if(!a) break;    //do something here    if(!b) break;    //do another thing here     }while(0);  //final step goes here}

当你执行一段代码到一半,想跳过剩下的一半的时候,如果你正处于do while循环中,则能用break达到这个目的。如:

do{  我执行.  我执行..  我再执行…  if (有什么条件满足了我)  {    呀,我想跳到另外一段代码了,剩下的不执行了,可是不建议用goto语句,怎么办呢?     break;/*看我的*/  }  我有可能被执行.  我有可能被执行..  我有可能被执行…}while(false)

这样做也可以是兼容各种编译器。

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

这种代码在只支持c89的编译器上是编译不过去的,比如ADS 2.0。

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

这种代码在各种编译器上都能编译过去。

为了宏展开的时候不会出错。如果直接放在花括号离会出错的,比如:

#define DO_SOMETHING {int time = 100 ;make_love(i);}

下面是使用的地方:

if(you->strong())DO_SOMETHING;else ..;

展开后是这样的:

if(you->strong()){int time = 100 ;make_love(i);};else ..;

那么编译就会出错,可以验证使用d0{}while(0)就不会出错,linux内核源码经常见这玩意。

假如a, b分别是两条c语句,定义一个顺序执行他们的宏有几种写法,比如:

#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)

前面几个都是有问题的,只有do while(0)解决得比较好。

0 0