Home >Backend Development >C++ >Is `(bool)true` Always Equivalent to `(int)1` in C ?
In C , it is a common practice to use typecasting to convert data from one type to another. This question explores whether we can safely assume the equivalence of (bool)true and (int)1 in C compilers.
The Equivalence
The conversion from bool to int is defined by the C standard in section 4.7 [conv.integral] / 4. It states that if the source type is bool, the value true is converted to one. This means that in the expression (bool)true == (int)1, the bool value will be promoted to an int and will have a value of 1.
Redundant Casting
The casts in the expression (bool)true == (int)1 are technically redundant. The bool value will be automatically promoted to an int by the compiler, and the comparison will work as expected without the explicit casts.
Compiler Compatibility
The equivalence between (bool)true and (int)1 is guaranteed by the C standard. As such, it is a safe assumption to make for any C compiler that adheres to the standard.
Conclusion
In C , we can safely assume (bool)true == (int)1 for all C compilers that follow the C standard. The typecasts are redundant and can be omitted without affecting the result of the comparison.
The above is the detailed content of Is `(bool)true` Always Equivalent to `(int)1` in C ?. For more information, please follow other related articles on the PHP Chinese website!