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