compl, ~

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Alternative Representations of Tokens (C++), Operators (C++)

Syntax

Description

The compl operator is an alternative representation of the ~ operator (bitwise NOT).

The word compl is the abbreviation for complement.

The operand of ~ must be an integral or enumeration type. The result is the one's complement of the operand. Integral promotions are performed.

To invert Boolean values, you should use the logical negation (operator !).

The type of the result is the type of the promoted operand.

There can be ambiguity in the ~X() unary expression, where X is a class name. The ambiguity is resolved in favor of treating ~ as a unary complement rather than treating ~X as a destructor.

In order to use the compl alternative for ~, you have to set the Enable new operator names option (the -VM compiler switch, available on the Compatibility page of the ProjectOptions dialog box).

Example

The following code represents a C++ console application. All the printed values are in base 16.

#include <tchar.h>
#include <iostream>
#include <iomanip>
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {
	cout << hex << setfill('0'); // display in hexadecimal format

	// the one's complement of 1 is not 0
	cout << setw(8) << ~((unsigned long)1) << endl;

	// use the alternative representation
	cout << setw(8) << compl((unsigned long)0xff) << endl;

	// the sign bit of a signed value is also inverted
	cout << setw(8) << ~((signed long) - 1) << endl;

	return 0; // put breakpoint here to see the console output
}

Console output

fffffffe
ffffff00
00000000