Chaining Bool values give opposite result to expected

后端 未结 5 1923
忘掉有多难
忘掉有多难 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:44

    The behaviour shouldn't be seen as odd. The grammar rules for == (and most but not all binary operators) specify left to right grouping so your original expression is equivalent to:

    !((((((0 == year) == month) == day) == hour) == minute) == second)
    

    Note that when compared to an integer type a bool expression with value true will promote to 1 and with value false will promote to 0. (In C the result of the equality operator is an int in any case with a value or either 1 or 0.)

    This means that, for example, ((0 == year) == month) will be true if year is zero and month is one or if year is non-zero but month is zero and false otherwise.

提交回复
热议问题