Can Bool and Int Equate in C Across Compilers?
In C , programmers often encounter the need to compare values of different types, such as bool and int. A common question arises: can we safely assume that (bool)true equals (int)1 for any C compiler?
Answer: Yes, but Casts are Redundant
The casts in the expression (bool)true == (int)1 are unnecessary. C automatically promotes the bool value to an int during the comparison. This promotion results in the value 1.
The behavior is defined by the C standard in [conv.integral] / 4:
"If the source type is bool... true is converted to one."
Therefore, the expression true == 1 is equivalent to 1 == 1, which is a true comparison. This behavior is consistent across all C compilers.
The above is the detailed content of Can `true` and `1` Always Be Considered Equal in C Comparisons Across Different Compilers?. For more information, please follow other related articles on the PHP Chinese website!