Recently I have read some chapters C++ Primer, there is one things which made me confused.
The book says:
There are four operators that do guarantee the order in which operands are evaluated.
the logical AND (&&) operator,
the logical OR (||) operator,
the conditional (? :) operator,
and the comma (,) operator.
And then I saw these codes:
if (val == true) { /* ... */ } // true only if val is equal to 1!
Then the book explain:
If val is not a bool, then true is converted to the type of val before the == operator is applied.
That is, when val is not a bool, it is as if we had written
if (val == 1) { /* ... */ }
Here is my question:
Why is the bool type true converted to arithmetic type, not the val instead? Is it involve the order of evaluation of equality operator?
Just as the book says only four operators guarantee the order, not including equality operator. So the result of the expression above should be undefined, am I right? If not, what it should be?
Looking forward to your reply. Thanks in advance.
It has nothing to do with the order of evaluation. The comparison operators always perform the usual arithmetic conversions on their operands. These conversions apply equally to both operands (although the order is unspecified). In the case in which a bool
is being compared to another integral type, the operand of type bool
is always promoted to int
first.