Two '==' equality operators in same 'if' condition are not working as intended

被刻印的时光 ゝ 提交于 2019-11-28 01:51:11
  if ( (i == j) == k )

  i == j -> true -> 1 
  1 != 123 

To avoid that:

 if ( i == j && j == k ) {

Don't do this:

 if ( (i==j) == (j==k))

You'll get for i = 1, j = 2, k = 1 :

 if ( (false) == (false) )

... hence the wrong answer ;)

You need to separate the operations:

  if ( i == j && i == k)

Expression

i == j == k

is parsed as

(i == j) == k

So you compare i to j and get true. Than you compare true to 123. true is converted to integer as 1. One is not equal 123, so the expression is false.

You need expression i == j && j == k

I'd heed the compiler's warning and write it as (i==j) && (j==k). It takes longer to write but it means the same thing and is not likely to make the compiler complain.

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