"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-18
Browse:662

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?

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).

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3