c++cbooleanoperator-precedence

Chaining Bool values give opposite result to expected


Unthinkingly I wrote some code to check that all the values of a struct were set to 0. To accomplish this I used:

bool IsValid() {
    return !(0 == year == month == day == hour == minute == second);
}

where all struct members were of type unsigned short. I used the code as part of a larger test but noticed that it was returning false for values differing from zero, and true for values that were all equal to zero - the opposite of what I expected.

I changed the code to read:

bool IsValid() {
    return (0 != year) || (0 != month) || (0 != day) || (0 != hour) || (0 != minute) || (0 != second);
}

But would like to know what caused the odd behaviour. Is it a result of precedence? I've tried to Google this answer but found nothing, if there's any nomenclature to describe the result I'd love to know it.

I compiled the code using VS9 and VS8.


Solution

  • == groups from left to right, so if all values are zero then:

    0 == year // true
    (0 == year) == month // false, since month is 0 and (0 == year) converts to 1
    ((0 == year) == month) == day // true
    

    And so on.

    In general, x == y == z is not equivalent to x == y && x == z as you seem to expect.