Skip to main content
The ^= operator is the bitwise XOR (exclusive OR) compound assignment operator in C++. It performs a bitwise XOR operation between the left and right operands, subsequently assigning the computed result to the left operand.

Syntax

For built-in types, this is logically equivalent to lhs = lhs ^ rhs;, with the critical technical distinction that the left-hand side expression (lhs) is evaluated exactly once. This prevents multiple evaluations when lhs contains side effects (e.g., array[i++] ^= 5;).

Bitwise Mechanics

The operator evaluates the operands bit by bit. For each corresponding bit position, it applies the standard XOR truth table: The resulting bit is 1 if and only if the bits at that position in the two operands differ.

Type Constraints and Overloading

The behavior and constraints of ^= depend on whether the built-in operator or a user-defined overload is invoked. Built-in Operator:
  • Valid Types: The built-in operator requires the left-hand operand (lhs) to be an integral type (e.g., int, char, short, long, and their unsigned variants). The right-hand operand (rhs) may be an integral type or an unscoped enumeration type.
  • Invalid Types: Floating-point types (float, double) and pointers are strictly prohibited. For the built-in operator, lhs cannot be an enumeration type because the XOR operation triggers integral promotion, yielding an integer result, and C++ forbids implicit conversion from an integer back to an enumeration.
  • Promotions: Standard integer promotions and usual arithmetic conversions are applied to bring both operands to a common type before the bitwise operation. The result is implicitly converted back to the type of lhs upon assignment.
Overloaded Operator:
  • C++ allows operator^= to be overloaded for user-defined types (classes and structs) and enumerations.
  • It is standard practice to overload operator^= for enumeration types so they can function as strongly-typed bitmasks.
  • Standard library types, such as std::bitset and std::valarray, provide their own overloads of ^= to perform bitwise XOR operations across their internal data structures.

Volatile Deprecation (C++20)

As of C++20, the use of compound assignment operators, including ^=, on volatile-qualified variables is deprecated. Expressions such as volatile_var ^= 5; will generate compiler warnings and may be ill-formed in future standard revisions.

Return Value

For built-in types, the ^= expression evaluates to an lvalue reference to the modified left operand. This allows the operator to be chained with other assignment operations, evaluated from right to left. User-defined overloads conventionally return an lvalue reference to *this to mirror this built-in behavior.

Code Visualization

Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More