C++ xor_eq
The xor_eq
keyword in C++ is an alternative representation for the bitwise XOR assignment operator (^=
). It is part of the set of alternative tokens provided by C++ for operators, often used to improve code readability or compatibility with certain keyboard layouts.
The xor_eq
operator performs a bitwise XOR operation between two values and assigns the result to the left operand.
Syntax
</>
Copy
operand1 xor_eq operand2;
- operand1
- The variable on which the XOR operation is performed and to which the result is assigned.
- operand2
- The value to XOR with
operand1
. - The result
- The result of the XOR operation is stored in
operand1
.
Examples
Example 1: Using xor_eq
for Bitwise XOR Assignment
In this example, we will show how to use xor_eq
keyword to modify a variable using the XOR assignment operation.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
a xor_eq b; // Perform XOR and assign the result to 'a'
cout << "Result of a xor_eq b: " << a << endl; // Output: 12 (Binary: 1100)
return 0;
}
Output:
Result of a xor_eq b: 12
Explanation:
a = 10 (Binary: 1010)
andb = 6 (Binary: 0110)
.- The XOR operation compares each bit of
a
andb
. If the bits are different, the result is1
; otherwise, it is0
. 1010 XOR 0110 = 1100 (Decimal: 12)
.- The result
1100
is assigned back toa
.
Example 2: Swapping Two Variables Using xor_eq
This example shows how to use xor_eq
to swap the values of two variables without using a temporary variable.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 9;
x xor_eq y; // Step 1: x = x XOR y
y xor_eq x; // Step 2: y = y XOR x
x xor_eq y; // Step 3: x = x XOR y
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}
Output:
After swapping: x = 9, y = 5
Explanation:
- Initially,
x = 5 (Binary: 0101)
andy = 9 (Binary: 1001)
. - Step 1:
x xor_eq y
results inx = 0101 XOR 1001 = 1100
. - Step 2:
y xor_eq x
results iny = 1001 XOR 1100 = 0101
(original value ofx
). - Step 3:
x xor_eq y
results inx = 1100 XOR 0101 = 1001
(original value ofy
). - The values of
x
andy
are successfully swapped without a temporary variable.
Key Points about xor_eq keyword
- The
xor_eq
keyword is equivalent to^=
and is used for bitwise XOR assignment operations. - It modifies the value of the left operand by performing a bitwise XOR operation with the right operand.
xor_eq
is one of the alternative tokens in C++ for operator representation.- While functional,
xor_eq
is rarely used in modern C++ code, as^=
is more commonly preferred for its conciseness.