C++ compl Keyword

The compl keyword in C++ is an alternative token for the bitwise complement operator (~). It is part of the alternative representations provided by C++ for certain operators, primarily to improve readability or to support environments where the original operator symbols are unavailable.

The bitwise complement operator inverts all the bits of its operand, flipping 0s to 1s and 1s to 0. It works with integral types such as int, long, and unsigned int.


Syntax

</>
Copy
compl operand;
compl
The keyword used as an alternative to the ~ operator for bitwise complement.
operand
An integral type variable whose bits will be inverted.

Examples

Example 1: Using compl to Invert Bits

This example demonstrates how to use the compl keyword to invert the bits of an integer.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int num = 5;   // Binary: 00000101
    int result = compl num;

    cout << "Original number: " << num << endl;
    cout << "Bitwise complement: " << result << endl;

    return 0;
}

Output:

Original number: 5
Bitwise complement: -6

Explanation:

  1. The variable num is initialized with the value 5 (binary: 00000101).
  2. The compl operator inverts the bits of num, resulting in 11111010 in binary, which corresponds to -6 in signed integer representation (two’s complement).
  3. The result is printed to the console, showing -6 as the bitwise complement of 5.

Example 2: Using compl with Unsigned Integers

This example demonstrates the use of the compl keyword with an unsigned integer.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    unsigned int num = 5;  // Binary: 00000101
    unsigned int result = compl num;

    cout << "Original number: " << num << endl;
    cout << "Bitwise complement: " << result << endl;

    return 0;
}

Output:

Original number: 5
Bitwise complement: 4294967290

Explanation:

  1. The variable num is an unsigned integer initialized with the value 5 (binary: 00000101).
  2. The compl operator inverts the bits, resulting in 11111111111111111111111111111010 in binary, which corresponds to 4294967290 in unsigned integer representation.
  3. The result is printed to the console, showing the bitwise complement of 5 as 4294967290.

Key Points about compl Keyword

  1. The compl keyword is an alternative representation for the ~ operator.
  2. It performs a bitwise complement operation, flipping all bits of the operand.
  3. The compl operator works with integral types such as int, long, and unsigned int.
  4. While functional, the compl keyword is rarely used, as the ~ operator is more commonly preferred for its simplicity.