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.
以上是bool 轉換為 int 是否保證為 0 或 1?的詳細內容。更多資訊請關注PHP中文網其他相關文章!