chapel

Unexpected result from i == j == k?


In this code I am looping over all indices in a 3D domain, and printing the "diagonal" part as

for (i, j, k) in {0..9, 0..9, 0..9}
{
    if i == j == k              // (1)
    //if (i == j) && (j == k)   // (2) -> gives expected result
    {
        writeln((i, j, k));
    }
}

My expected result is something like

(0, 0, 0)
(1, 1, 1)
(2, 2, 2)
(3, 3, 3)
(4, 4, 4)
(5, 5, 5)
(6, 6, 6)
(7, 7, 7)
(8, 8, 8)
(9, 9, 9)

which is obtained with Line (2) above. But if I use Line (1), it gives an unexpected result like

(0, 0, 1)
(0, 1, 0)
(0, 2, 0)
...
(9, 7, 0)
(9, 8, 0)
(9, 9, 1)

So I am wondering if I am erroneously using i == j == k? (FYI, the above code is motivated by some Python code like

for i in range(10):
    for j in range(10):
        for k in range(10):

            if i == j == k:
                print( i, j, k )

which gives (0, 0, 0), (1, 1, 1), ...)


Solution

  • Right on, @Someprogrammerdude.

    == is a binary operator, it is left-associative. The documentation is here:

    https://chapel-lang.org/docs/language/spec/expressions.html#precedence-and-associativity

    When comparing the boolean (i==j) with the integer k (in the context of i==j==k), the boolean is implicitly converted to an integer and an integer equality check is performed.