"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > In C++ and C, is it always 0 or 1 when converted to an integer?

In C++ and C, is it always 0 or 1 when converted to an integer?

Posted on 2025-04-13
Browse:531

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3