Chaining Bool values give opposite result to expected

后端 未结 5 1913
忘掉有多难
忘掉有多难 2020-12-17 15:32

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 ==          


        
5条回答
  •  一个人的身影
    2020-12-17 15:40

    == 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.

提交回复
热议问题