One's complement operator: ~


~ cast-expression


The one's complement operator (~), sometimes called the bitwise complement operator, yields a bitwise one's complement of its operand. That is, every bit that is 1 in the operand is 0 in the result. Conversely, every bit that is 0 in the operand is 1 in the result. The operand to the one's complement operator must be an integral type.

Operator keyword for ~

C++ specifies compl as an alternative spelling for ~. In C, the alternative spelling is provided as a macro in the <iso646.h> header. In C++, the alternative spelling is a keyword; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.


// expre_One_Complement_Operator.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;

int main () {
   unsigned short y = 0xFFFF;
   cout << hex << y << endl;
   y = ~y;   // Take one's complement
   cout << hex << y << endl;

In this example, the new value assigned to y is the one's complement of the unsigned value 0xFFFF, or 0x0000.

Integral promotion is performed on integral operands. The type the operand is promoted to is the resultant type. For more information on integral promotion, see Standard conversions.

See also

Expressions with unary operators
C++ built-in operators, precedence, and associativity
Unary arithmetic operators