Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ~ operator in C++ is the unary bitwise NOT operator, also known as the one’s complement operator. It evaluates its operand and returns a value where every bit of the operand’s binary representation has been inverted: every 0 becomes a 1, and every 1 becomes a 0.

Syntax

~expression

Operand and Type Requirements

The operand must be of an integral type or an unscoped enumeration type. Before the bitwise inversion occurs, C++ applies integral promotions to the operand:
  • Types smaller than int (e.g., char, signed char, unsigned char, short, unsigned short) are promoted to int (or unsigned int if int cannot represent all values of the original type).
  • The bitwise inversion is performed on the promoted type.
  • The result is a prvalue (pure rvalue) of the promoted type.

Bitwise Mechanics and Integral Promotion

Because of integral promotion, applying ~ to smaller integer types alters the bit width of the evaluated expression.
#include <cstdint>
#include <type_traits>

uint8_t val = 0b00001111; // Decimal 15

// 'val' is promoted to a 32-bit int before inversion:
// 00000000 00000000 00000000 00001111
// After ~ operation:
// 11111111 11111111 11111111 11110000
auto result = ~val; 

static_assert(std::is_same_v<decltype(result), int>); // True

Mathematical Equivalence

In C++20 and later, signed integers are strictly defined to use two’s complement representation. Under two’s complement arithmetic, the bitwise NOT operation is mathematically equivalent to negating the value and subtracting one:
int x = 5;
int y = ~x; // y is -6
// ~x == -x - 1

Operator Overloading

The ~ operator can be overloaded for user-defined types. When overloaded as a non-member function, it takes exactly one parameter. When overloaded as a member function, it takes no parameters.
struct CustomType {
    int value;
    
    // Member function overload
    CustomType operator~() const {
        return CustomType{~value};
    }
};

Destructor Token

Distinct from its role as an expression operator, the ~ token is also used syntactically in class definitions to declare a destructor. In this context, it acts as a declarative identifier prepended to the class name and does not perform a bitwise operation.
class Resource {
public:
    Resource();  // Constructor
    ~Resource(); // Destructor
};
Master C++ with Deep Grasping Methodology!Learn More