Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way in C++ for converting a builtin type (int) to bool?

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. (...)

like image 464
Martin Ba Avatar asked Dec 04 '22 09:12

Martin Ba


2 Answers

In the context of using win32 SDK and MFC, I tend to write it always this way. It's explicit.

bool b = (myBOOL != FALSE);

EDIT: I have edited :-) cause i'm not sure myBOOL == TRUE works for all implementation of BOOL and I can assume that FALSE may have the 0 value most of the time.

like image 161
Stephane Rolland Avatar answered Dec 11 '22 12:12

Stephane Rolland


The correct way I'd assume is:

bool b = static_cast<bool>(val);
like image 42
Viktor Sehr Avatar answered Dec 11 '22 12:12

Viktor Sehr