为什么你会使用三元运算符不分配一个值的"真"条件(X = X:1) [英] Why would you use the ternary operator without assigning a value for the "true" condition (x = x ?: 1)

查看:216
本文介绍了为什么你会使用三元运算符不分配一个值的"真"条件(X = X:1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android开源QEMU code我碰到这条线code跑了:

In the Android open-source qemu code I ran across this line of code:

machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */

这是随便说的一个令人困惑的方式:

Is this just a confusing way of saying:

if (machine->max_cpus) {
   ; //do nothing
} else {
 machine->max_cpus = 1;
}

如果是这样,那岂不是更清晰的:

If so, wouldn't it be clearer as:

if (machine->max_cpus == 0) machine->max_cpus = 1;

有趣的是,编译并正常工作与海湾合作委员会,但没有就 http://www.comeaucomputing.com/tryitout/

推荐答案

这是的在GNU许可作为一个不起眼的延伸到C

This is permitted in GNU as an obscure extension to C

5.7条件语句省略操作数

5.7 Conditionals with Omitted Operands

在有条件的中间操作数
  前pression可以省略。然后,如果
  第一个操作数非零,它的值是
  有条件的价值
  前pression。

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.

因此​​,前pression

Therefore, the expression

 x ? : y


  
  

有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.

正如你可能已经猜到,避免这种建议的可读性和可移植性的原因。我很诚实地惊讶地看到这样的语法不兼容扩展到C

As you can probably guess, avoiding this is recommended for readability and portability reasons. I'm honestly surprised to see such a grammar-incompatible extension to C.

这篇关于为什么你会使用三元运算符不分配一个值的"真"条件(X = X:1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆