Question:
Is it guaranteed that the value stored in a bool variable will be either 0 or 1 when it is converted to an integer (int)?
Answer:
Yes, it is guaranteed.
Reason:
Both the C and C programming languages specifically define the behavior of bool values when they are converted to integers.
In C , the C Standard (§4.5/4) 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, the C Standard (§6.3.1.2/1) states:
"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 a _Bool value is converted to int, the value remains the same as it is, since int can hold both 0 and 1 (§6.3.1.3).
Therefore, you can rely on the fact that a bool variable will always contain either 0 or 1 when converted to an int.
The above is the detailed content of Is a bool variable guaranteed to convert to 0 or 1 when cast to an integer?. For more information, please follow other related articles on the PHP Chinese website!