看到开放源代码,宏定义经常这样用

#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)能够确保无论在代码中怎么使用宏定义。它总是正确的。