Operator precedence and ternary operator

狂风中的少年 提交于 2019-12-02 04:45:36
Nishu Tayal

Your conditions are not properly written.

In the first if-statement:

  if (a ? b : c == 0)

if you put the values, then it becomes

if(10 ? 0 : 7 == 0)

means, it will always return 0.

That's why control goes to the else part and there, it becomes

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

since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".

Now you want that code should return "1", then change your if statement in this way.

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

because "==" operator has higher precedence than ternary operator.

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) { ... }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!