Home > Backend Development > C++ > Is bool Conversion to int Guaranteed to Be 0 or 1?

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

DDD
Release: 2024-11-15 09:42:02
Original
375 people have browsed it

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

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.

The above is the detailed content of Is bool Conversion to int Guaranteed to Be 0 or 1?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template