do{}while(0)只执行一次无意义?你可能真的没理解

1.有时候只是为了代码分块,比仅仅使用{}更直观些。例如在cocos2d-x代码中
do
{
    CCImage* pImage = new CCImage();
    CC_BREAK_IF(NULL == pImage);
    bRet = pImage->initWithString(text, (int)dimensions.width, (int)dimensions.height, eAlign, fontName, (int)fontSize);
    CC_BREAK_IF(!bRet);
    bRet = initWithImage(pImage);
    CC_SAFE_RELEASE(pImage);
} while (0);
2.为了宏展开的时候不会出错。如果直接放在花括号里会出错的
#define DOSOMETHING()   do{action1(); action2();}while(0)
3.当你执行一段代码到一半,想跳过剩下的一半的时候,如果你正处于do{...}while(0)循环中,则能用break达到这个目的。
do
{
  执行.
  再执行…
  if (如果有什么条件满足)
  {
    我想跳到另外一段代码了,剩下的不执行了,可是不建议用goto语句,怎么办呢?
     break;/*搞定*/
  }
  我有可能被执行.
}while(false)

举个例子如下

do
{
  if(!a) break;
  //do something here
  if(!b) break;
  //do another thing here   
}while(0);
4.变形的goto,有些公司不让用goto。在一些函数中,需要实现条件转移,或者构成循环,跳出循环体,使用goto总是一种简单的方法
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char *str;
   /* 最初的内存分配 */
   str = (char *) malloc(15);
   if(str != NULL)
     goto loop;
   printf("hello world\n");
loop:
   printf("malloc success\n");
   return(0);
}

但由于goto不符合软件工程的结构化,而且有可能使得代码难懂,所以很多人都不倡导使用,这个时候我们可以使用do{...}while(0)来做同样的事情:

#include <stdio.h>
#include <stdlib.h>
int main()
{
  do{
      char *str;
      /* 最初的内存分配 */
      str = (char *) malloc(15);
      if(str != NULL)
       break;
      printf("hello world\n");
  }while(0);
   printf("malloc success\n");
   return(0);
}
5.可以兼容各种编译器
int a;
a = 10;
int b;
b = 20;

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

int a;
a = 10;
do
{
   int b;
   b = 20;
}while(0);
6.避免由宏引起的警告,内核中由于不同架构的限制,很多时候会用到空宏。在编译的时候,这些空宏会给出警告,为了避免这样的warning,我们可以使用do{...}while(0)来定义空宏
#define  DOSOMETHING()  do{}while(0)
7.定义单一的函数块来完成复杂的操作

如果你有一个复杂的函数,变量很多,而且你不想要增加新的函数,可以使用do{...}while(0),将你的代码写在里面,里面可以定义变量而不用考虑变量名会同函数之前或者之后的重复,例如

int key;
string value;
int func()
{
    int key = GetKey();
    string value = GetValue();
    dosomething for key,value;
    do{
        int key;string value;
        dosomething for this key,value;
    }while(0);    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。