总结:
do{…}while(0)在宏定义中的作用:使用do{…}while(0)构造后的宏定义不会受到大括号、分号等语句格式的影响,适用于各种场合下的调用。
在C项目中,宏是提高程序可读性和算法性能必不可少的部分。而在linux内核源码和许多库中,我们经常会看到被频繁使用的宏会出现do{…}while(0)。
例如:#define func(x) do{dosomething(x);}while(0)
为什么要这样定义呢?
这样写更简单呀:#define func(x) dosomething(x) 这样写也没错,但如果换成: #define func(x) dosomething(x) ;dootherthing(x)
很容易知道在某些情况下是有毛病的:
if (flag) 等价于 if (flag)
func(x); dosomething(x) ;
dootherthing(x);
很明显就错误了。那改成;#define func(x) { dosomething(x) ;dootherthing(x);}呢
在某些情况下也是有毛病:
if (flag)
func(x) ;
else
fun1(x);
等价于
if (flag)
{ dosomething(x) ;dootherthing(x);};
else
fun1(x);
就出现语法错误啦。
如果使用#define func(x) do{ dosomething(x) ;dootherthing(x);}while(0)就不会出现上述的错误啦!
if (flag)
do{ dosomething(x) ;dootherthing(x);}while(0);
if (flag)
do{ dosomething(x) ;dootherthing(x);}while(0);
else
fun1(x);
利用了do{…}while 循环语句一定会执行一次循环体内容的特性,并通过while(0)结束循环语句。