Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-15 08:41:03
Original
362 people have browsed it

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
Copy after login

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.

The above is the detailed content of Is Bool Conversion to Int Always 0 or 1 in C and C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template