在开源代码中看到,宏定义经常这样用
变为
这样直接加个花括号不久行了,为什么还用do......while()?假如加上花括号
变为
#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)的原因,通过对比不同宏定义方式,解释了这种方式如何确保宏定义在各种使用场景下的正确性。

2518

被折叠的 条评论
为什么被折叠?



