Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Bitwise NOT operator ~

The unary ~ operator flips the bits of a value after integral promotions. It is not the logical negation operator !. A mask lets you retain only selected bits of the complemented result.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

~expression

The built-in operator ~expression changes every 0 bit to 1 and every 1 bit to 0. It accepts an integral or unscoped enumeration operand; the result has the operand's type after integral promotions. Evaluating ~value alone does not modify value.

Promotions matter: unsigned char is promoted to int if int can represent all its values, and otherwise to unsigned int. The operation therefore flips the bits of the promoted type, not just those of the original narrow type. bool is also promoted to int.

Do not confuse ~ with !: ! produces a logical result of type bool, whereas ~ flips bits. In the example, value and mask have type unsigned int. The expression (~value) & mask retains only the lowest four bits, changing 0101 to 1010, or 10. On its own, ~value also flips the higher bits.

The example targets C++23 compilation mode. The displayed code was run unchanged in an isolated environment, and its standard output matched the expected output exactly. The supplied source is an evolving working draft of the standard, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    constexpr unsigned int value = 0b0101u;
    constexpr unsigned int mask = 0b1111u;
    constexpr unsigned int inverted = (~value) & mask;
    static_assert(inverted == 10u);
    std::cout << inverted << '\n';
}

Result

10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources