内核里的do{}while(0)

为啥内核里有这么多 do{ }while(0) 的宏啊?一开始我也好不明白。感觉不出用了会有什么效果。不过明白之后就知道它的好处了。好处就在于多语句的宏。

#define FOO(x)	print(”arg is %sn”,x);do_something(x);

在代码中使用:

if(2==blah)

	FOO(blah);

预编译展开后:

if(2==blah)

	print(”arg is %sn”,blah);

do_something(blah);

看到了吧,do_something函数已经脱离了if语句的控制了。这可不是我们想要的。使用do{}while(0);就万无一失了。

if (2== blah)

  do {

	printf(”arg is %sn”, blah);

	do_something(blah);

  } while (0);

当然你也可以使用下面这种形式:

#define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }

但是它在if-else语句中会出现问题。如:
if (x > y)

	exch(x,y);          // Branch 1

else

	do_something();     // Branch 2

展开后:

if (x > y) {                // Single-branch if-statement!!! 

	int tmp;            // The one and only branch consists

	tmp = x;            // of the block.

	x = y;

	y = tmp;v};                           // empty statementelse          

 // ERROR!!!   “parse error before else”do_something();

看到了吧,else成了语法错误了。使用do{}while(0)就不会有这个问题了。

if (x > y)

do {

	int tmp;

	tmp = x;

	x = y;

	y = tmp;

} while(0);

else

	do_something();

嗯,现在明白之后,自己的代码也记得用啊! 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值