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:
- The variable
numis initialized with the value5(binary:00000101). - The
comploperator inverts the bits ofnum, resulting in11111010in binary, which corresponds to-6in signed integer representation (two’s complement). - The result is printed to the console, showing
-6as the bitwise complement of5.
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:
- The variable
numis an unsigned integer initialized with the value5(binary:00000101). - The
comploperator inverts the bits, resulting in11111111111111111111111111111010in binary, which corresponds to4294967290in unsigned integer representation. - The result is printed to the console, showing the bitwise complement of
5as4294967290.
Key Points about compl Keyword
- The
complkeyword is an alternative representation for the~operator. - It performs a bitwise complement operation, flipping all bits of the operand.
- The
comploperator works with integral types such asint,long, andunsigned int. - While functional, the
complkeyword is rarely used, as the~operator is more commonly preferred for its simplicity.
