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

2019-03-11 04:23发布

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);

4条回答
Ridiculous、
2楼-- · 2019-03-11 04:36

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楼-- · 2019-03-11 04:44

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.

查看更多
何必那么认真
4楼-- · 2019-03-11 04:59

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;
查看更多
相关推荐>>
5楼-- · 2019-03-11 04:59

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.

查看更多
登录 后发表回答