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
!
if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.
The equality operator (==) is used to compare two values or expressions. It is used to compare numbers, strings, Boolean values, variables, objects, arrays, or functions.
The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With