内核代码中一个逗号表达式比较特别的用法

内核代码sch_fifo.c中有这么一行代码:

CODE:
u32 limit = sch->dev->tx_queue_len ? : 1;


在另外一个地方,看到有朋友分析这段代码时,提到了这个执行的结果是limit取sch->dev->tx_queue_len的值,如果该值小于1,则至少为1.

我们常用的"? :"是三目运算符,这里好像没有“:”左边没有任何成员。

写了个测试程序,大致总结如下:
(1)如果"?" 左边就是数值的话,只要其不为0,limit就取它的值,否则为1;
(2)如果"?"左边是一个表达式的话,如果表达式的结果为0,则limit取1,否则则取表达式的结果。

这是实践中得到的分析结果。

下面是gcc的解释:

 

Conditionals with Omitted Operands

The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.

Therefore, the expression

     x ? : y
     

has the value of x if that is nonzero; otherwise, the value of y.

This example is perfectly equivalent to

     x ? x : y
     

In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

 

一个测试代码:

#define INC(x) (++x)

int x = 0;
int y = 0;


那么

y = INC(x) ? INC(x) : 3


y = INC(x) ? : 3


这也就是“?:”省略中间操作数,可以避免边界效应

 

转自:http://linux.chinaunix.net/bbs/thread-1142378-1-1.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值