do{} while(0)好处

替代{},实现局部作用域.

#define fun() \
    do { fun1(); fun2(); } while(0)
if (condition) fun(); else { ... }; // ok 

// compared with

#define fun() {fun1(); fun2(); }
if (condition) fun(); else { ... }; // compile error; 

避免使用goto,用break做跳出.

do {
    fun1();
    ...
    fun2();
    if (condition) {
        break;
    }
    fun3();
    fun4();
} while(0);

shiyang6017
158 声望59 粉丝