大家都知道,do…while(condition)可以表示循环,但你有没有遇到在一些宏定义中可以不用循环的地方,也用到了 do…while.比如:
#define DELETE_POINTER(p) \
do \
{ \
if(NULL != p) \
delete p; \
p = NULL; \
}while(0)
这时,do…while(0)的功能就不仅仅是循环了,这是do..while(0)的一种巧妙用法。它有以下几种功能:
1.在后面要加分号,使调用如同函数;
调用如下:
int* p = new int(5);
DELETE_POINTER(p);
2.避免if else 不匹配;
举例说明如下:
#define PRINT_STRING(isDoc) \
if(isDoc) \
printDoc();
bool isReady = false;
bool isDoc = true;
if(isReady)
PRINT_STRING(isDoc);
else
doOtherThing();
则此代码相当于
bool isReady = false;
bool isDoc = true;
if(isReady)
if(isDoc)
printDoc();
else
doOtherThing();
还有其它的一些用法 ,有人总结的很清楚了,这是不在累赘。
原文:http://www.spongeliu.com/415.html
网友评论