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);
That's between you and your compiler, but Microsoft thinks you should write:
in preference to either:
or
Possible reasons for preferring it include:
if (buf != NULL)
orif (buf != 0)
in preference toif (buf)
after a call tomalloc
,I do as someone already posted:
It's the easier way imo and the it's more intuitive than trying to cast the integer to bool.
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:
This is the only logically correct way of converting an
int
tobool
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
toint
is just lazy. Make the mapping explicit: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:
This never gives warnings.