Question:
Many compilers appear to store bool values as either 0 or 1, but is this behavior guaranteed? Specifically, in the following snippet:
int a = 2; bool b = a; int c = 3 + b; // 4 or 5?
Answer:
Yes, bool values are guaranteed to be converted to either 0 or 1 when converted to int. This behavior is defined in both the C and C standards:
C (§4.5/4):
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
C (§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.
Therefore, in the given example, b will be converted to either 0 (if a is not equal to 0) or 1 (if a is equal to 0). Adding 3 to b will result in either 4 or 5, depending on the value of a.
The above is the detailed content of Is bool Conversion to int Guaranteed to Be 0 or 1?. For more information, please follow other related articles on the PHP Chinese website!