Home >Backend Development >C++ >Is Bool-to-Int Conversion Truly Portable Across C and C99?
Bool to Int Conversion: A Detailed Examination of Portability
In certain programming scenarios, the conversion of bool to int values becomes necessary. However, concerns arise regarding its portability across different platforms. This article provides a comprehensive analysis of the portability of this conversion, addressing the question of whether we can confidently expect the following assertions to pass:
int x = 4 < 5; assert(x == 1); x = 4 > 5; assert(x == 0);
Standard Conformant Conversion
The bool-to-int conversion in C is implicitly defined by the C standard. According to §4.7/4 of the C 11 or 14 standard, and §7.8/4 of the C 17 standard, "If the source type is bool, the value false is converted to zero and the value true is converted to one." This means that:
Therefore, the conversion of bool to int is completely portable and standard-conformant in C .
Consideration for C
C99 introduced the _Bool type, which is a fundamental integer type. stdbool.h also introduces bool, true, and false macros. Section 7.16 of the C99 standard states that true expands to the integer constant 1, while false expands to 0. Hence, these macros behave similarly to bool conversion in C .
Conclusion
The bool-to-int conversion is portable across different platforms that support C and C99 or later. Programmers can be assured that the assertions shown in the beginning of this article will pass successfully in both languages. We recommend using the standard bool type for maximum portability and clarity.
The above is the detailed content of Is Bool-to-Int Conversion Truly Portable Across C and C99?. For more information, please follow other related articles on the PHP Chinese website!