How to best convert VARIANT_BOOL to C++ bool?

sharptooth picture sharptooth · May 20, 2009 · Viewed 22.4k times · Source

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:

  1. compare with VARIANT_FALSE

  2. 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?

Answer

1800 INFORMATION picture 1800 INFORMATION · May 20, 2009

Compare to VARIANT_FALSE. There is a lot of buggy code out there that mistakenly passes in the C++ bool true value (cast to the integer value 1) to a function expecting VARIANT_BOOL. If you compare to VARIANT_FALSE, you will still get the correct expected value.