bool to int Conversion: A Deep Dive into Its Portability
Original Question:
How portable is the conversion of a bool value to an int? Can we be certain that the following assertions pass on all systems?
int x = 4 < 5; assert(x == 1); x = 4 > 5; assert(x == 0);
Answer:
Yes, the conversion of bool to int is completely portable and compliant with both C and C standards.
Explanation:
In C , the conversion from bool to int is implicit, as specified in the C Standard (§4.7/4 from the C 11 or 14 Standard, §7.8/4 from the C 17 Standard, §7.3.9/2 from the 20 Standard). According to these standards:
In our example:
int x = 4 < 5;
Exactly translates to:
int x = true;
Since true is converted to one, the assertion will pass. Similarly, in the second assertion, false is converted to zero, resulting in an assertion success.
Additional Information for C:
Prior to C99, C did not have a bool type. However, C99 introduced the _Bool type and the macro bool (defined in the stdbool.h header file) that expands to _Bool. The macros true and false are also defined in the same header file, where true expands to the integer constant 1, and false expands to the integer constant 0.
According to §7.16 from C99:
#define bool _Bool #define true 1 #define false 0
Therefore, the bool to int conversion in C99 and later behaves similarly to C .
The above is the detailed content of How Portable is Boolean to Integer Conversion in C and C ?. For more information, please follow other related articles on the PHP Chinese website!