do...while(0)的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28110727/article/details/80474312
为什么需要使用do...whie(0),我们都知道do{...}while(condition)可以表示循环,但我们会遇见一些宏定义中可以不用循环的地方,使用到了do{...}while(0)。
ex:
#define foo(x) do{\
statement1;\
statement2;\
}while(0)
在初次遇见这样的宏定义的过程中会觉得比较奇怪,既然循环里面的语句只执行了一次,为什么会需要看似多余的do...while(0)有什么意义。我们为什么不直接写出如下表达。
错误一:
#define foo(x)
{
statement1;\
statement2;\
}
我们都知道宏在预处理的过程中会被直接展开

对于上面的例子,在vs会直接提示错误,原因是
if(condition)
{
statement1;
statement2;
};
else
...

错误二:
#define Foo(x) (x)+=1;(x)+=1;

if(condition)
Foo(x)
else
...
会被展开成
if(condition)
(x)+=1;
(x)+=1;
else
...
这样会被导致else语句孤立而出现编译错误。


总结:通过do{...}while(0)我们使得宏能够被正确的展开,保留原始的语义,从而保证程序的正确性。

猜你喜欢

转载自blog.csdn.net/qq_28110727/article/details/80474312