why is such a code allowed?


Let say:
    int a = 5;
    int b = 7;
    int i = 20;
    if ((a == b) + i) {
        a = 15;
My question is:
The expression (a == b) gives a bool result.
Why is it allowed to add a "bool" and an "int".


From a C perspective this makes perfect sense as there is no “bool” types, if statements branch based on a value not being zero rather than not being logically true.

From a C++ perspective, where the typing is more strict, I have copied this bit from the Microsoft C++ site which was the first thing I could find on the subject and I assume is standard conforming:

The bool type participates in integral promotions. An r-value of type bool can be converted to an r-value of type int, with false becoming zero and true becoming one. As a distinct type, bool participates in overload resolution.

Hi Guy,

C89 doesn’t have the concept of “bool” - all comparisons return an int (or is it an unsigned int?) in the range [0,1].

C99 and C++ build on C89 so even though they have the concept of “bool”, the type of a comparison was not changed.



[Even though this C-language question seems easy enough for me to answer, I am certain that a true language lawyer will pipe up and tell me I’m wrong :wink: ]

The paragraph in question (C++11) Is 4.7/4. The second sentence covers the particular case in question.

If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one.

As for why, it can be useful to add a bool to an integer that is counting the number of times a function passed. Then you can just write myBool += FunctionToTest(); rather than some conditional block.