Double structural equality operators: if(a==b==c)

前端 未结 2 1957
臣服心动
臣服心动 2021-01-01 17:17

I wrote some code by accident today and was surprised when Eclipse did not yell at me, for once. The code had a double use of the structural equality operator (==

相关标签:
2条回答
  • 2021-01-01 18:03

    Playing around, I notice I can't do if(a==b==c) with any type but boolean.

    You can't do it with any type but boolean because this comparison chain will be evaluated from the left side to the right. First comparison will be simplified to true or false value which has to be compared with the third value in chain (and result of this check will be compared to fourth value and so on, till the end of the chain). As for the primitive values, you can only compare primitives of the same type (e.g. boolean and boolean will work, while double and boolean won't) - that's why you can do it with booleans only - because the == returns the value of the same type as all the values in chain.
    There's danger here: the result of all that comparison chain isn't equal to true when all values you've provided are true. You can see it from the second output: true == false == false raises true, which is right result if you evaluate it from left to right (as it happens during the program execution), but may seem wrong if you think that this comparison chain has to be evaluated all at once. The correct way to do it is two perform two explicit comparisons:

    if (a == b && b == c) {
        // do something
    }
    
    0 讨论(0)
  • 2021-01-01 18:08

    The == operator is left-associative, so a == b == c is interpreted as (a == b) == c. So a == b returns a bool, which is then compared to c.

    This is a side effect of the parser that is rarely useful in practice. As you've observed, it looks like it does one thing but does something very different (so even if it does what you want, it's not recommended). Some languages actually make the == operator non-associative, so a == b == c is a syntax error.

    0 讨论(0)
提交回复
热议问题