123
分类: C/C++
2013-07-17 17:02:46
原文地址:三目运算符“?:”省略中间操作数的分析 作者:Godbach
|
|
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. |
|
[root@localhost tmp]# ./a.out y=2 y=1 |
表达式y = INC(x) ? INC(x) : 3
中宏INC(x)进行了两次扩展。因此,导致x被计算了两次,最终结果为2。而表达式y = INC(x) ? : 3
仅对宏INC(x)进行了一次扩展,因此,最终的结果为1。
这也就是“?:”省略中间操作数的用途。当然,如果像表达式
u32 limit = sch->dev->tx_queue_len ? : 1
中第1个操作数表达方法比较长时
,而又想当期不为0时就取本身的值,也可以使用这种方式,节省了代码的长度。