C macro : the " do { ... } while(0)" magic

在读Linux源码的时候看到一堆这种macro:

#define FOO(X) do { f(X); g(X); } while (0)

一直想不明白,为什么不直接用

#define FOO(X) f(x);g(x);

或者:

#define FOO(X) {f(x);g(x);}

 

搜了一下才明白:

  http://stackoverflow.com/questions/9495962/why-use-do-while-0-in-macro-definition

  http://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-c-c-macros

 

 

 

真是源码面前,了无秘密。虽然不可能全盘读完,但是读得越多,发现的黑科技越多。

 

 

 

 

 

 

 

 

 

:)

posted @ 2016-05-02 11:55  walkerlala  阅读(259)  评论(0编辑  收藏  举报