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扩展.
可以省略条件表达式中的中间操作数.然后,如果第一个操作数非零,则其值为条件表达式的值.
因此,表达
Run Code Online (Sandbox Code Playgroud)x ? : y具有
xif非零的值; 否则,价值y.这个例子完全等同于
Run Code Online (Sandbox Code Playgroud)x ? x : y在这个简单的例子中,省略中间操作数的能力并不是特别有用.当它变得有用时是第一个操作数,或者可能(如果它是一个宏参数),包含副作用.然后在中间重复操作数将执行两次副作用.省略中间操作数使用已经计算的值而没有重新计算它的不良影响.