小编Sak*_*mar的帖子

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

我在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).

c ternary-operator conditional-operator

13
推荐指数
3
解决办法
1191
查看次数

标签 统计

c ×1

conditional-operator ×1

ternary-operator ×1