Home > Backend Development > C++ > Is a bool variable guaranteed to convert to 0 or 1 when cast to an integer?

Is a bool variable guaranteed to convert to 0 or 1 when cast to an integer?

Linda Hamilton
Release: 2024-11-12 14:46:02
Original
563 people have browsed it

Is a bool variable guaranteed to convert to 0 or 1 when cast to an integer?

Guaranteed Values of Bool When Converted to Int

Question:

Is it guaranteed that the value stored in a bool variable will be either 0 or 1 when it is converted to an integer (int)?

Answer:

Yes, it is guaranteed.

Reason:

Both the C and C programming languages specifically define the behavior of bool values when they are converted to integers.

In C , the C Standard (§4.5/4) states:

"An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one."

In C, the C Standard (§6.3.1.2/1) states:

"When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1."

When a _Bool value is converted to int, the value remains the same as it is, since int can hold both 0 and 1 (§6.3.1.3).

Therefore, you can rely on the fact that a bool variable will always contain either 0 or 1 when converted to an int.

The above is the detailed content of Is a bool variable guaranteed to convert to 0 or 1 when cast to an integer?. 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