Home > database >  How to elegantly flip a BOOL, without a warning?
How to elegantly flip a BOOL, without a warning?

Time:08-18

I want to simply flip a BOOL variable, but this generates a lnt-logical-bitwise-mismatch warning.

Is there an elegant solution to this?

BOOL bCloseButtons = FALSE;
bCloseButtons = !bCloseButtons;                 // Intellisense generate a logical-bitwise mismatch
bCloseButtons = bCloseButtons ? FALSE : TRUE;   // works, but not elegant in my eye
CButton m_btnPumpP1;
BOOL bLocked = FALSE;
m_btnPump_P1.EnableWindow(!bLocked);           // Intellisense generate a logigal-bitwise mismatch
m_btnPump_P1.EnableWindow(!((bool)bLocked))    // horrible, not readable

CodePudding user response:

Use a bool value in your code instead. Flipping a bool is a simple matter of applying the unary !-operator, e.g. value = !value;.

Passing a bool value into an API that expects a BOOL (aka int) value implicitly performs integral promotion from bool to int. This is well defined and will not trigger any warnings.

Likewise, if a BOOL return value needs to be converted to a value of type bool, that conversion is also implicit. The value 0 becomes false, and all other values become true. This will not raise any warnings either. If code wants to be explicit about this conversion the following expression produces a bool value following the implicit conversion rules: value_abi != FALSE.


A bit of rationale: BOOL is a type alias for a signed 32-bit integer. It exists solely to describe an API in a way that's ABI-stable, so that code compiled today will continue to run a decade from now without having to be recompiled. It is strictly there to establish a binary contract between the caller and the implementation of a function.

It's not generally useful to keep those ABI types in client code. If you are modeling a flag in C , then clearly a boolean value is the most appropriate type. When it comes time to pass this value into an API you would then convert it to the expected ABI type. In case of a bool value this is done automatically as part of the integral type promotion rules of the C programming language. At other times you may have to explicitly perform the conversion, though that is extremely rare.

  • Related