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);
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);
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;
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:
if (buf != NULL)
or if (buf != 0)
in preference to if (buf)
after a call to malloc
,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.
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.