`return x 是什么? : 1`在C语言中是什么意思?

What does `return x ? : 1` mean in C language?

我在 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?
}

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

#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;
}

得到如下输出

f 1
f 1

当我将其更改为

int f(int x)
{
        return x?:2;
}

我得到

f 2
f 1

我只想知道标准中是否提到了这种行为(return 1,如果没有提到)。

这是一个GCC extensionx?:2x?x:2 相同(then 部分计算一次)

C 标准中未提及此行为。它是 GCC extension

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.

根据GCC extension

The middle operand in a conditional expression may be omitted

return x?:1;是写return x?x :1;

的简写方法

这是普通三元运算符的 GNU C 扩展。 X ?: YX ? X : Y 相同,只是 X 仅计算一次。