This explains a surprising corner of C++ bitmask operations: integral promotion and boolean conversion interact so that complementing true yields true. With P4313-style enum bitmask ops that convert an enum to its underlying integral type, promotions to int are mandatory; complementing true promotes 1 to int, ~1 becomes -2, and casting back to bool converts any non‑zero to true. If an enum uses bool as its underlying type and operator~ casts via to_underlying, the result is true by the standard; however, a long‑standing GCC conformance bug instead truncates to the low bit when converting back to the enum, producing false. Clang and MSVC follow the standard and produce true.
Unscoped enums without a fixed underlying type add another hazard: promotion rules choose an int if it can represent the enum’s value range even when the compiler stores the enum in unsigned int, so bitwise ~ can produce negatives and comparisons fail. More importantly, such enums define a value range as an M‑bit integer; casting values outside that range back to the enum is undefined behavior. Bitwise ops (especially ~ and <<) can easily produce out‑of‑range results, so user‑defined operators that cast back to the enum can invoke UB. Practical mitigations: forbid bool as an underlying type, detect unfixed enums (e.g., via a T{0} initialization test) and constrain operators accordingly.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.