do{}while(0)宏的作用的定义

看到开放源代码,宏定义经常这样用
#define	some()					
	do {								
		do_somt_thing();
	} while (0)

为什么这样用?

能够试一下。假如一个普通宏定义

#define some(x) Fun1(x);Fun2(x)

if(condition)
	some(x);

变为

if(condition)
	Fun1(x);
	Fun2(x);

这样直接加个花括号不久行了,为什么还用do......while()?假如加上花括号

#define some(x) {Fun1(x);Fun2(x);}

if(condition)
	some(x);
else
	someelse(x);

变为

if(condition)
{
	Fun1(x);
	Fun2(x);
};//多了个分号
else
	someelse(x);


因此宏定义中使用do...while(0)能够确保无论在代码中怎么使用宏定义。它总是正确的。


版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-07-01 16:57  zfyouxi  阅读(200)  评论(0编辑  收藏  举报