首頁 > 後端開發 > C++ > C 和 C 中 Bool 轉換為 Int 總是 0 或 1 嗎?

C 和 C 中 Bool 轉換為 Int 總是 0 或 1 嗎?

Susan Sarandon
發布: 2024-11-15 08:41:03
原創
442 人瀏覽過

Is Bool Conversion to Int Always 0 or 1 in C++ and C?

Bool Conversion to Int: Guaranteed to Be 0 or 1?

In programming languages like C++ and C, bool is commonly used to represent boolean values of true and false. However, behind the scenes, these values are often stored as integers. This raises the question: when a bool is converted to an int, is the result guaranteed to be either 0 or 1?

C++

In C++, the answer is a resounding yes. According to the C++ standard (§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." This means that when a bool is converted to an int in C++, the result will always be 0 or 1.

C

In C, the situation is slightly different but equally clear. According to the C standard (§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." This implies that when a bool (represented as _Bool in C) is converted to an int, the result will again be 0 or 1.

Practical Example

To illustrate this behavior in code:

int a = 2;
bool b = a;
int c = 3 + b; // 4
登入後複製

In this example, the bool variable b is initialized to the value of int a (which is 2), but since bool values are stored as 0 or 1, b becomes 1. The subsequent addition of 3 results in c being assigned the value 4. This confirms that bool is converted to int as 1, guaranteeing a result of 0 or 1.

以上是C 和 C 中 Bool 轉換為 Int 總是 0 或 1 嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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