Nusrat Nuriyev
Nusrat Nuriyev

Reputation: 1174

Does cout treat bool as integer or integer as bool?

Why does this program

int a = 8; 
cout << a && true ;
cout << typeid(a && true).name();

output

8bool

Frankly, I expected "truebool" or "8int".

Is operator << of cout object involved in this or is it a precedence issue?

Does it convert true to 1 as in the case when we cout << true;? typeid(a && true) gives us bool, though the cout << a && true; is obviously a number?

Upvotes: 2

Views: 257

Answers (1)

paddy
paddy

Reputation: 63471

Indeed it is an operator precedence issue. << has a higher precedence than &&.

One shorthand trick you can use to interpret an integer value to bool is to double-NOT it:

cout << !!a;

This is a matter of style, which may be divisive within the C++ community. So, if you don't want to be controversial, then the following may be more acceptable:

cout << (a ? true : false);
cout << static_cast<bool>(a);
cout << (a != 0);

Personally, I think that (a && true) is somewhat ugly. But I'm sure there are some who would argue otherwise.

In the end, the compiler should be generating the same result no matter how you write it.

Upvotes: 4

Related Questions