分类: LINUX
2011-05-13 14:48:55
/*
* Author: Godbach
* Blog:http://blog.chinaunix.net/u/33048/index.html
* 本文欢迎自由转载,但请标明出处,并保证本文的完整性。
*/
内核代码sch_fifo.c中函数fifo_init的代码如下:
static int fifo_init(struct Qdisc *sch, struct rtattr *opt) |
u32 limit = sch->dev->tx_queue_len ? : 1; |
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 ? : yhas the value of x if that is nonzero; otherwise, the value of y. This example is perfectly equivalent to x ? x : yIn 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. |
A side effect is a result of an operator, expression, statement, or function that persists even after the operator, expression, statement, or function has finished being evaluated.
原来 x ? : y 就是 x ? x : y。
但是,通常情况下用 x ? : y 替换x ? x : y看起来并不是很友好,至少我看着觉得有些别扭。根据上面的分析,在某些情况下,在表达式x为宏定义的时候,使用x ? : y 代替x ? x : y,可以避免有些宏定义产生的边界效应。请看下面的实例代码:
#include <stdio.h> |
[root@localhost tmp]# ./a.out y=2 y=1 |
====
http://hi.baidu.com/whs08/blog/item/bd5ede73cd1f5d178601b0e8.html