The complement of true is true, except when it's false
The complement of true, in most cases, is true. However, there is an exception when it comes to bool. In C++, when you perform a bitwise complement operation on true and then cast the result back to a bool, the outcome is true. This is because the boolean conversion truncates the value, replacing the discarded bit pattern with true. The same happens when you try to evaluate the complement of true and cast the result to a bool – the result is always true.
The situation becomes more complicated when using enums as bitmasks. Enums can be defined with any integral type as their underlying type, including bool. To perform bitwise complement operations on enums, a template function is typically used. This function converts the enum to its underlying type, applies the bitwise operation, and then casts the result back to the enum. However, this can lead to confusion as the result of the complement operation may not be what is expected.
When using gcc, the result of the complement operation on an enum may differ from the expected result. For example, if an enum is defined with bool as its underlying type, gcc will truncate the result to the lowest bit rather than perform a boolean conversion. This means that even values will result in bool::FALSE, while odd values will result in bool::TRUE. This behavior is specific to enum types and not directly applicable to bool.
On the other hand, compilers like Clang and MSVC evaluate the result of complement-and-cast operations consistently, following the standard rules. This means that the complement of true and the complement of any enum value will always result in true.
One potential issue arises when using an unsigned int as the underlying type for an enum. In this case, the integral promotion rules introduce a new vector for undefined behavior. If you try to perform a complement operation on an enum value using an unsigned int as its underlying type, the result may fail to compile. This is because the comparison reduces to a value that is not equal to zero, leading to a static assertion failure.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.