When using COM boolean values are to be passed as VARIANT_BOOL which is declared in wtypes.h as short. There are also predefined values for true and false:
#define VARIANT_TRUE ((VARIANT_BOOL)-1)
#define VARIANT_FALSE ((VARIANT_BOOL)0)
Which is the best way to convert from VARIANT_BOOL to C++ bool
type? Obvious variants are:
compare with VARIANT_FALSE
simply cast to bool
Other ways can be easily invented.
Which is the best way to do this - most readable, most standart-compliant, least prone to accidential bugs planting and least prone to issues with porting to 64-bit platforms?
Why have an explicit cast?
This way, true is true and false is false, as per the C standard. If you need to SET a C++ style
bool
then do something like:I don't like to have to worry about compatibility between different boolean values, so I will normally write:
Are there tinier (as in "will compile to simpler x86 code"), valid ways to do it? Of course. Not worth it. This is guaranteed to work, so I can worry about my business logic.
Casting to bool is obviously wrong. Some people say (e.g. comments at BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool) to compare to VARIANT_FALSE, but I would compare to both. That way you catch invalid values (anything but VARIANT_FALSE or VARIANT_TRUE) early.
e.g.
Declare this macro in one of your global headers.
EDIT: Much safer version:
Compare to
VARIANT_FALSE
. There is a lot of buggy code out there that mistakenly passes in the C++ booltrue
value (cast to the integer value 1) to a function expectingVARIANT_BOOL
. If you compare toVARIANT_FALSE
, you will still get the correct expected value.Standard C++ conversion rules rely on zero meaning false [and as 1800 INFORMATION points out, the TRUE variant is where the most confusion happens] and nothing more. Hence a static_cast would be best.
But in many cases, the code would be more readable as a comparison. In that case, VARIANT_BOOL is the thing to compare with.