do{ }while (0);
通过do-while(0)宏定义将代码打包起来,成为一个独立的语法单元,从而不会引起上下文混淆,同时因为绝大多数的编译器都能够识别do{…}while(0)这种无用的循环并进行优化,所以使用这种方法也不会导致程序的性能降低。下面是两个例子。
Imagine a macro of several lines of code like:
#define FOO(x) \ printf("arg is %s\n", x); \ do_something_useful(x);
if (blah == 2) FOO(blah);
if (blah == 2) printf("arg is %s\n", blah); do_something_useful(blah);;
if (blah == 2) do { printf("arg is %s\n", blah); do_something_useful(blah); } while (0);
#define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }
However that wouldn't work in some cases. The following code is meant to be an if-statement with two branches:
if (x > y) exch(x,y); // Branch 1 else do_something(); // Branch 2
But it would be interpreted as an if-statement with only one branch:
if (x > y) { // Single-branch if-statement!!! int tmp; // The one and only branch consists tmp = x; // of the block. x = y; y = tmp; } ; // empty statement else // ERROR!!! "parse error before else" do_something();
if (x > y) do { int tmp; tmp = x; x = y; y = tmp; } while(0); else do_something();