C++'s complement of true is true, except when GCC says it's false
The complement of true is true, except when it's false
A standards proposal for bitmask operations on enums leads to a deep dive into C++ integer promotion quirks. Integral promotion forces small types up to int, and boolean conversion maps any nonzero value to true. So ~true becomes true. But GCC disagrees for enums backed by bool, truncating instead of converting, and unscoped enums can trigger undefined behavior when bitwise results fall outside their value range.
There you have it, the complement of true is true, or spelled in C++ static_cast<bool>(~true) == true.
- Panzerschrek
With such example:
bool Complement( bool x )
{
return ~x;
}
GCC gives a warning if compiling with -Wall:
test.cpp:3:10: warning: ‘~’ on an expression of type bool [-Wbool-operation]
return ~x;
So, it's surprise that C++ does this, but ones who enable compiler warnings are not in trouble.
- rep_lodsb
They should have defined true as -1 (all bits set) instead, as in some other languages like Forth and BASIC.
- s-zeng
In any field of characteristic 2, every element is its own negative. So on the surface this makes sense, notwithstanding the unintuitive enum corner case behaviour