c - 为什么要使用三元运算符而不为 "true"条件赋值 (x = x ? : 1)

标签 c gcc android-emulator conditional-operator qemu

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

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

这只是一种令人困惑的说法吗:

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

如果是这样,不是更清楚:

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

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

最佳答案

这是 permitted在 GNU 中作为 C 语言的模糊扩展

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.

Therefore, the expression

 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 扩展,我真的很惊讶。

关于c - 为什么要使用三元运算符而不为 "true"条件赋值 (x = x ? : 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2806255/

相关文章:

java - Android Studio 找不到 cerfile,模拟器无法启动

android - 如何在android中将输入类型数字更改为EditText的文本

c - 互斥锁 vs 忙等待 tcp io

c++ - 为什么 stoi 函数在 Visual Studio 2010 中可用

将地址传递给数组而不是数组会导致问题吗?

c++ - 按值传递结构,并将另一个结构作为其成员之一,会更改该成员的成员的值

c++ - OS X 10.8上的gcc 4.8编译错误

ubuntu - Alt+Tab 后 Android 模拟器窗口保持在顶部

c - 非法指令 CMOVE - 为 i586 编译

c - 如何评估C中的输入数据?