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