How to best convert VARIANT_BOOL to C++ bool? How to best convert VARIANT_BOOL to C++ bool? windows windows

How to best convert VARIANT_BOOL to C++ bool?


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.


I don't like to have to worry about compatibility between different boolean values, so I will normally write:

VARIANT_BOOL vb_bool = VARIANT_FALSE;// ... vb_bool set to something by some other codebool myBool = (vb_bool == VARIANT_TRUE);

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.

bool VariantBoolToBool(VARIANT_BOOL varFlag){  bool boolFlag;  switch( varFlag )   {    case VARIANT_TRUE:        boolFlag = true;        break;    case VARIANT_FALSE:        boolFlag = false;        break;    default:        throw Exception("Not a valid value");  }  return boolFlag;}