Home >Backend Development >C++ >Is Bool-to-Int Conversion Portable in C and C ?
bool to int Conversion
Consider the following code snippet:
int x = 4 < 5; assert(x == 1); x = 4 > 5; assert(x == 0);
The question arises: is this conversion portable? Can we guarantee that both assertions pass?
Answer:
Yes, this conversion is completely portable and compliant with the C Standard. The explicit conversion from bool to int is implicit in C , as defined in §4.7/4 of the C 11 or 14 Standard, and §7.8/4 of the C 17 Standard.
Specifically, the Standard states: "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Therefore, in the given code:
Note for C:
In C, a bool data type is not present. However, C99 introduces the _Bool type, which is a macro defined in the stdbool.h header file. Additionally, true and false are macros that expand to integer constants 1 and 0, respectively.
Therefore, in C:
The above is the detailed content of Is Bool-to-Int Conversion Portable in C and C ?. For more information, please follow other related articles on the PHP Chinese website!