Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ bools converted to ints during comparison?

Tags:

c++

When using comparison operators in C++, are bools converted to ints?

The reason I ask is that the question of whether or not to always explicitly compare to true/false in if-statements came up. The two options being:

1) if (my_bool == true) doSomething();
2) if (my_bool) doSomething();

We were thinking you should generally avoid the explicit comparison (1) because of the following:

int myFunc(){return 4;}
if (myFunc() == true) doSomething();

Something like the code above would come up if you need to work with C interfaces that simply return nonzero to indicate "true". The myFunc() example would fail in C because myFunc returns 4, true is macro'd to 1, and 4 == 1 is not true.

Is this still the case in C++? Does the "equal to" operator convert the bool to an int rather than the other way around? References to the standard (C++11 is what I'm working with) are appreciated, but if it differs among versions of the language I'd be interested in knowing.

(I'd like to ask specifically about the pros/cons of explicit true/false comparison, but that seems like it could be subjective.)

like image 786
josaphatv Avatar asked Mar 15 '16 23:03

josaphatv


2 Answers

They are not converted, bool actually ARE integer types.

See the standard:

"Values of type bool are either true or false. As described below, bool values behave as integral types. Values of type bool participate in integral promotions" ~ C++03

like image 23
ig343 Avatar answered Sep 30 '22 17:09

ig343


When using comparison operators in C++, are bools converted to ints?

Yes. For relational operators ([expr.rel]/5):

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type.

For equality operators ([expr.eq]/6):

If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands;

When both operands are bool, they are both promoted to int. If one operand is a bool and the other is of integral type, the bool operand is promoted to int. See [expr]/10:

Otherwise, the integral promotions (4.5) shall be performed on both operands.

As far as I know, this has been true since the beginning of time (it does not differ between revisions of the standard).

I do not think there is any performance implication of doing explicit comparison to true or false, but I wouldn't do it myself, since I consider it redundant and not in a way that yields any benefit.

like image 78
Brian Bi Avatar answered Sep 30 '22 18:09

Brian Bi