Comparison of bool data types in C++
§4.5 of the C++ standard says:
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
regarding 2 and 3, type conversion takes place so the statements will work as desired
According to the rule of Boolean conversions:
A prvalue of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to a prvalue of type
bool
.The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become
false
. All other values becometrue
.
Then
bool x = 1; // x will be true
bool y = 0; // y will be false
bool z = 1; // z will be true
For the 1st case, if (x==1)
, x
will be promoted to int
,
the type
bool
can be converted toint
with the valuefalse
becoming 0
andtrue
becoming1
.
then (x==1)
is true
.
For the second case, if (y>0.5)
, y
will be promoted to int
with value 0
, then converted to double
for the comparison;
If the operands has arithmetic or enumeration type (scoped or unscoped), usual arithmetic conversions are performed on both operands following the rules for arithmetic operators. The values are compared after conversions:
and
If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion.
...
- Otherwise, if either operand is
double
, the other operand is converted todouble
then y>0.5
is false
.
For the third case, if (z>0.5)
, z
will be promoted to int
with value 1
, then converted to double
for the comparison; then z>0.5
is true
.