Home > Enterprise >  Does cout treat bool as integer or integer as bool?
Does cout treat bool as integer or integer as bool?

Time:11-26

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?

CodePudding user response:

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.

  • Related