首頁 > 後端開發 > C++ > bool 轉換為 int 是否保證為 0 或 1?

bool 轉換為 int 是否保證為 0 或 1?

DDD
發布: 2024-11-15 09:42:02
原創
384 人瀏覽過

Is bool Conversion to int Guaranteed to Be 0 or 1?

bool Conversion to int: Guaranteed to be 0 or 1?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板