Home >Backend Development >C++ >How Does C Implicitly Convert Boolean Values to Integers?
Implicit Conversion: bool to int Transformation
In C , a non-intuitive conversion occurs when assigning a bool expression to an int variable. Consider the following code snippet:
int x = 4 < 5; assert(x == 1); x = 4 > 5; assert(x == 0);
Conversion Details
According to the C Standard (§4.7/4 in C 11/14, §7.8/4 in C 17, §7.3.9/2 in C 20):
Therefore, in the given code, 4 < 5 evaluates to true, which is converted to 1 and stored in x, while 4 > 5 evaluates to false, which is converted to 0 and stored in x.
Portability
This implicit bool to int conversion is portable across all C platforms.
Comparison to C
Unlike C , C does not explicitly support the bool datatype prior to the C99 standard. However, the C99 standard introduced the _Bool type, which is equivalent to bool in C . In C99, the macros true and false expand to the integer constants 1 and 0, respectively. As a result, the bool to int conversion behavior is similar in both C and C .
Conclusion
The implicit bool to int conversion in the given code is standard conformant and portable across C platforms. While it may seem unorthodox, it is essential for understanding the underlying behavior of the C language.
The above is the detailed content of How Does C Implicitly Convert Boolean Values to Integers?. For more information, please follow other related articles on the PHP Chinese website!