C宏(macro)定义——do{...}while(0)

C语言中,有时处于效率方面的考虑,采用宏的方式来替代函数。C定义宏时,常采用如下方式:

1 #define MACRO_FUNC(arg) do{ \
2 ... \
3 }while(0)

为什么要加do { .. }while(0)这样一段看似毫无用处的代码呢?这是为了保证宏方法(function)和普通方法调用方式的统一。下面来看例子:

1 #define FOO(x) foo(x); bar(x);
1 if(condition) 
2     FOO(x);
3 else// syntax error here
4     ...;
即使加上"{}"都没有用:
1 #define FOO(x){ foo(x); bar(x);}
1 if(condition) 
2     FOO(x);
3 else// syntax error here
4     ...;
只能这样:
1 if(condition) 
2     FOO(x)// 没有";"
3 else
4     ...
或者:
1 if(condition){
2     FOO(x);
3 } 
4 else
5     ...
这样的方式来调用宏方法。但是这两种方式都破坏了宏方法(function)和普通方法调用方式的统一性。如果采用下面的方式定义:
1  #define FOO(x) do{ foo(x); bar(x);}while(0)           
1 if(condition)
2     FOO(x);//OK!!!
3 else
4     ....                                  
参考链接:
        http://stackoverflow.com/questions/1067226/c-multi-line-macro-do-while0-vs-scope-block
         http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for

 

posted @ 2013-03-27 14:09  Apprentice_  阅读(434)  评论(0编辑  收藏  举报