简体   繁体   English

运算符优先级和三元运算符

[英]Operator precedence and ternary operator

I have a problem in C.我在C有问题。

#include<stdio.h>
int main()
{
    int a = 10, b = 0, c = 7;
    if (a ? b : c == 0)
        printf("1");
    else if (c = c || a && b)
        printf("2");
    return 0;
}

This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?此代码打印 2,但我认为 a?b:c 返回 b=0,0==0 返回 1。您能解释一下代码吗?

The conditional operator ( ?: ) has one of the lowest precedences.条件运算符 ( ?: ) 具有最低的优先级之一。 In particular it is lower than == .特别是它低于== Your statement means this:你的陈述是这样的:

if(a ? b : (c == 0)) { ... }

Not this:不是这个:

if((a ? b : c) == 0) { ... }

Your conditions are not properly written.你的条件没有写好。

In the first if-statement:在第一个 if 语句中:

  if (a ? b : c == 0)

if you put the values, then it becomes如果你输入值,那么它就变成了

if(10 ? 0 : 7 == 0)

means, it will always return 0.意味着,它将始终返回 0。

That's why control goes to the else part and there, it becomes这就是为什么控制转到 else 部分,在那里,它变成了

else if (7 = 7 || 10 && 0)

since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".由于您在此处使用了“=”运算符 (c = c),因此它将始终为真,因此它会打印“2”。

Now you want that code should return "1", then change your if statement in this way.现在您希望该代码返回“1”,然后以这种方式更改您的 if 语句。

 if( (a ? b:c) == 0){...}

because "==" operator has higher precedence than ternary operator.因为“==”运算符的优先级高于三元运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM