hn.today

The complement of true is true, except when it's false

dryperspective.github.io23 points2 comments
Screenshot of The complement of true is true, except when it's false

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.

Read on dryperspective.github.io2 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Worth Building

Worth Building

Building tools without the need to monetize allows for more personal, enjoyable, and quick development of useful applications. This shift enables more people to create small, polished tools for their own needs or ideas, regardless of broader market appeal. (armstr.ng)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.