为什么要使用三元运算符而不为“真"赋值?条件 (x = x ?: 1) [英] Why would you use the ternary operator without assigning a value for the "true" condition (x = x ?: 1)

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

问题描述

在 Android 开源 qemu 代码中我遇到了这行代码:

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;

有趣的是,这可以在 gcc 上编译并正常工作,但不能在 http://www.comeaucomputing 上编译.com/tryitout/ .

Interestingly, this compiles and works fine with gcc, but doesn't compile on 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

条件中的中间操作数表达式可以省略.那么如果第一个操作数非零,其值为条件的值表达.

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.

因此,表达式

 x ? : y

如果 x 不为零,则其值为 x;否则,y的值.

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

这个例子完全等价到

 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天全站免登陆