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

前端 未结 2 1983
臣服心动
臣服心动 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: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.

提交回复
热议问题