Double structural equality operators: if(a==b==c)
java
Solution
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
}
Problem
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 (`==`) similar to the below with the `if(a==b==c)` structure. ``` public class tripleEqual { public static void main(String[] args) { boolean[] a = { true, false }; boolean[] b = { true, false }; boolean[] c = { true, false }; for (int aDex = 0; aDex < 2; aDex++) { for (int bDex = 0; bDex < 2; bDex++) { for (int cDex = 0; cDex < 2; cDex++) { if (a[aDex] == b[bDex] == c[cDex]) { System.out.printf("Got a==b==c with %d %d %d\n", aDex, bDex, cDex); } } } } } } ``` The output is ``` Got a==b==c with 0 0 0 Got a==b==c with 0 1 1 Got a==b==c with 1 0 1 Got a==b==c with 1 1 0 ``` Playing around, I notice I can't do `if(a==b==c)` with any type but `boolean`. From that the boolean expression is ``` ( A'. B'. C') + ( A'. B . C ) + ( A . B'. C ) + ( A . B . C') ``` which simplifies to `(A=B).'C + (A<>B).C`. Thus, ignoring side-effect, `if(a==b==c)` is equal to `if(a==b && !c) || (a!=b && c))`. Can anyone explain how the `if(a==b==c)` syntax suggests that? Edit 1: I found where my confusion was after so many people explained the left-associativity. Usually I write '1' for true and '0' for false but my minimized truth table/output in the above test, I had '0' for true and '1' for false. The negation of the expression `( A'. B'. C') + ( A'. B . C ) + ( A . B'. C ) + ( A . B . C')` is `(A=B)=C`!