如何在没有警告的情况下优雅地翻转 BOOL?

Tom*_*Tom 1 c++ winapi

我想简单地翻转一个BOOL变量,但这会生成一个lnt-逻辑位不匹配警告。

有一个优雅的解决方案吗?

BOOL bCloseButtons = FALSE;
bCloseButtons = !bCloseButtons;                 // Intellisense generate a logical-bitwise mismatch
bCloseButtons = bCloseButtons ? FALSE : TRUE;   // works, but not elegant in my eye
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

IIn*_*ble 9

请改用bool代码中的值。翻转 abool是应用一元运算符的简单问题!,例如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.