Why does casting an int to a bool give a warning?

2019-03-11 04:45发布

问题:

Shouldn't it be ok to use static_cast to convert int to bool as it converts reverse of implicit conversion but i still get a warning?

Example:

MSVC++ 8

bool bit = static_cast<bool>(100);

回答1:

Just because the conversion a => b is implicit doesn’t say anything about the viability of the reverse, b => a.

In your case, you shouldn’t cast at all. Just do the obvious thing: compare:

bool result = int_value != 0;

This is the only logically correct way of converting an int to bool and it makes the code much more readable (because it makes the assumptions explicit).

The same applies for the reverse, by the way. Converting implicitly from bool to int is just lazy. Make the mapping explicit:

int result = condition ? 1 : 0;


回答2:

That's between you and your compiler, but Microsoft thinks you should write:

i != 0

in preference to either:

(bool)i

or

static_cast<bool>(i)

Possible reasons for preferring it include:

  • this conversion doesn't act like other narrowing conversions, that take a modulus,
  • the implict conversions to bool are also a bit controversial: plenty of people prefer to do if (buf != NULL) or if (buf != 0) in preference to if (buf) after a call to malloc,
  • the comparison is both shorter and clearer.


回答3:

I'm not sure why it happens when you explicitly cast it (i think it was a performance warning?), but I usually use code like this to avoid any warnings:

int i;
bool b = (0!=i);

This never gives warnings.



回答4:

I do as someone already posted:

bool result = int_value != 0;

It's the easier way imo and the it's more intuitive than trying to cast the integer to bool.