Math-like chaining of the comparison operator - as in, “if ( (5<j<=1) )” [duplicate]

雨燕双飞 提交于 2020-01-08 13:25:29

问题


int j=42;
if( (5<j<=1) ) {
    printf("yes");
} else {
    printf("no");
}

Output:

yes

Why does it output yes?
Isn't the condition only half true?


回答1:


C does not understand math-like syntax, so

if(1<j<=5)

is not interpreted as you expect and want; it should be

if (1 < j && j <= 5)

or similar.

As explained in other answers, the expression is evaluated as

 ((1 < j) <= 5)

 =>  ("true" <= 5)

 =>  "true"

where "true" (boolean value) is implicitly converted to 1, as explaneid e.g. here, with references to standards too, and this explain why "true" has to be "less than" 5 (though in C might not be totally correct to speak about "implicit conversion from bool to int")




回答2:


As per operator precedence and LR associativity,

1<j evaluates to 1

1<=5 evaluates to 1

if(1)
{ 
  printf("yes")



回答3:


Your question is a bit broken, but I believe that the following will clarify what is going on for you:

In C, 1 < j <= 5 means the same thing as (1 < j) <= 5. And the value of 1 < j is 0 or 1 depending on whether is less than or equal to 1 or strictly greater than 1. So here is what happens for a few values of j in your code:

If j == 0, this expression is (1 < 0) <= 5, which reduces to 0 <= 5 (because 1 < 0 is false). This is a true expression. Your program outputs "yes".

If j == 3, this expression is (1 < 3) <= 5, which reduces to 1 <= 5 (because 1 < 3 is true). This is a true expression. Your program outputs "yes".

If j == 6, this expression is (1 < 6) <= 5, which reduces to 1 <= 5 (because 1 < 6 is true). This is a true expression. Your program outputs "yes".

In all cases, your program outputs "yes" because 1 < j is either 0 or 1, and either way it is less than 5.

What you should have used is 1 < j && j <= 5.




回答4:


what you want to write is if ( 1 < j && j <= 5 )

what is happening in your case is: if ( 1 < j <=5 )
1 < j is evaluated first, and it is true so it is evaluated to 1 and your condition becomes
if (1 <=5), which is also true so printf("yes"); gets excuted



来源:https://stackoverflow.com/questions/20989496/math-like-chaining-of-the-comparison-operator-as-in-if-5j-1

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