What is the preferred way in C++ for converting a builtin type (int) to bool?
Posted
by
Martin
on Stack Overflow
See other posts from Stack Overflow
or by Martin
Published on 2011-01-31T14:50:08Z
Indexed on
2011/01/31
15:25 UTC
Read the original article
Hit count: 293
When programming with Visual C++, I think every developer is used to see the warning
warning C4800: 'BOOL' : forcing value to bool 'true' or 'false'
from time to time. The reason obviously is that BOOL is defined as int and directly assigning any of the built-in numerical types to bool
is considered a bad idea.
So my question is now, given any built-in numerical type (int, short, ...) that is to be interpreted as a boolean value, what is the/your preferred way of actually storing that value into a variable of type bool
?
Note: While mixing BOOL and bool is probably a bad idea, I think the problem will inevitably pop up whether on Windows or somewhere else, so I think this question is neither Visual-C++ nor Windows specific.
Given int nBoolean;
I prefer this style:
bool b = nBoolean?true:false;
The following might be alternatives:
bool b = !!nBoolean;
bool b = (nBoolean != 0);
Is there a generally preferred way? Rationale?
I should add: Since I only work with Visual-C++ I cannot really say if this is a VC++ specific question or if the same problem pops up with other compilers. So it would be interesting to specifically hear from g++ or users how they handle the int->bool case.
Regarding Standard C++: As David Thornley notes in a comment, the C++ Standard does not require this behavior. In fact it seems to explicitly allow this, so one might consider this a VC++ weirdness. To quote the N3029 draft (which is what I have around atm.):
4.12 Boolean conversions [conv.bool]
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. (...)
© Stack Overflow or respective owner