Home >Backend Development >C++ >Is Bool-to-Int Conversion Portable in C and C ?

Is Bool-to-Int Conversion Portable in C and C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 02:50:15169browse

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:

  • 4 < 5 evaluates to true, which is implicitly converted to 1 and stored in x.
  • 4 > 5 evaluates to false, which is implicitly converted to 0 and stored in x.

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:

  • 4 < 5 evaluates to the integer value 1.
  • 4 > 5 evaluates to the integer value 0.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn