什么'返回x?:1`表示C语言?

Sak*_*mar 13 c ternary-operator conditional-operator

我在Linux内核源代码(2.6.32)中遇到了以下代码.

do_wait_for_common(struct completion *x, long timeout, int state)
{
        if (!x->done) {
        /* some code here */
        }
        x->done--;
        return timeout ?: 1; <--- What it returns?
}
Run Code Online (Sandbox Code Playgroud)

为了理解这种行为,我手动尝试了以下代码

#include <stdio.h>
int f(int x)
{
        return x?:1;
}
int main()
{
        printf("f %d\n", f(0));
        printf("f %d\n", f(1));
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

并得到以下输出

f 1
f 1
Run Code Online (Sandbox Code Playgroud)

当我改变它

int f(int x)
{
        return x?:2;
}
Run Code Online (Sandbox Code Playgroud)

我正进入(状态

f 2
f 1
Run Code Online (Sandbox Code Playgroud)

我只是想知道标准中是否提到了这种行为(如果没有提到则返回1).

hac*_*cks 16

C标准中未提及此行为.它是GCC扩展.

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

因此,表达

 x ? : y
Run Code Online (Sandbox Code Playgroud)

具有xif非零的值; 否则,价值y.

这个例子完全等同于

 x ? x : y  
Run Code Online (Sandbox Code Playgroud)

在这个简单的例子中,省略中间操作数的能力并不是特别有用.当它变得有用时是第一个操作数,或者可能(如果它是一个宏参数),包含副作用.然后在中间重复操作数将执行两次副作用.省略中间操作数使用已经计算的值而没有重新计算它的不良影响.


Bas*_*tch 13

这是GCC的延伸.x?:2是相同的x?x:2(当时部分评估一次)


bam*_*s53 5

这是普通三元运算符的GNU C扩展.X ?: Y是相同的X ? X : Y,除了X仅被评估一次.