Home > Backend Development > C++ > How Portable is Boolean to Integer Conversion in C and C ?

How Portable is Boolean to Integer Conversion in C and C ?

Barbara Streisand
Release: 2024-12-05 01:09:11
Original
1063 people have browsed it

How Portable is Boolean to Integer Conversion in C and C  ?

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);
Copy after login

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:

  • False is converted to zero.
  • True is converted to one.

In our example:

int x = 4 < 5;
Copy after login

Exactly translates to:

int x = true;
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template