do while(false)实用技巧

今天看项目源码的时候发现有些地方用了do{} while(false)的用法,查了下发现这样确实有些优点,mark下。

1.最重要的优点,用在略微复杂的宏定义中。

#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.当你执行一段代码到一半,想跳过剩下的一半的时候,如果你正处于do while循环中,则能用break达到这个目的。如下伪代码:

int foo()
{
    somestruct *ptr = malloc(...);

    dosomething...;
    if(error)
        goto END;
    dosomething...;
    if(error)
        goto END;
    dosomething...;
END:
    free(ptr);
    return 0;
}

避免goto语句的话,实用do while(false)就能很好的解决。

int foo()
{
    somestruct *ptr = malloc(...);
    do
    {
        dosomething...;
        if(error)
            break;
        dosomething...;
        if(error)
            break;
        dosomething...;
    }
    while(0);

    free(ptr);
    return 0;
}
posted @ 2016-10-04 14:48  chenhuan001  阅读(1295)  评论(0编辑  收藏  举报