内核代码sch_fifo.c中函数fifo_init的代码如下:
static int fifo_init(struct Qdisc *sch, struct rtattr *opt) { struct fifo_sched_data *q = qdisc_priv(sch); if (opt == NULL) { u32 limit = sch->dev->tx_queue_len ? : 1; if (sch->ops == &bfifo_qdisc_ops) limit *= sch->dev->mtu; q->limit = limit; } else { struct tc_fifo_qopt *ctl = RTA_DATA(opt); if (RTA_PAYLOAD(opt) < sizeof(*ctl)) return -EINVAL; q->limit = ctl->limit; } return 0; }
u32 limit = sch->dev->tx_queue_len ? : 1;
这里发现使用了三目运算符,但是又省略的中间的操作数。这是什么用法呢?网上发帖问了别的朋友,得到链接http://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Conditionals.html#Conditionals上介绍少,内容如下:
Conditionals with Omitted OperandsThe 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 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. |
#include <stdio.h> #define INC(x) (++x) int main(int argc, char *argv[]) { int x = 0; int y = 0; y = INC(x) ? INC(x) : 3; printf("y=%d\n", y); x = 0; y = INC(x) ? : 3; printf("y=%d\n", y); return 0; }
[root@localhost tmp]# ./a.out y=2 y=1 |
原帖:http://blog.chinaunix.net/uid-10167808-id-26005.html