Home > Backend Development > C++ > Does Converting a Boolean to an Integer Always Result in 0 or 1?

Does Converting a Boolean to an Integer Always Result in 0 or 1?

Linda Hamilton
Release: 2024-12-01 03:39:19
Original
426 people have browsed it

Does Converting a Boolean to an Integer Always Result in 0 or 1?

Can a Boolean Always Become Zero or One When Converted to an Integer?

When converting a boolean value to an integer, many compilers seemingly retain only 0 or 1, raising questions about the reliability of this behavior. Let's examine an example:

int a = 2;
bool b = a;
int c = 3 + b; // What is the result? 4 or 5?
Copy after login

Answer: Yes, bool is guaranteed to be 0 or 1 when converted to an integer.

In C :

The C standard (§4.5/4) explicitly states: "An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one."

In C:

When a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1): "When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1."

When converting to int, the process is straightforward because int can hold 0 and 1, so there's no change in value (§6.3.1.3).

The above is the detailed content of Does Converting a Boolean to an Integer Always Result in 0 or 1?. 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