Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Bitwise XOR assignment operator (^=)

The ^= operator performs bitwise exclusive OR. In the XOR calculation, ones in the mask flip the corresponding bits and zeros leave them unchanged. Before storing the result, the operator converts it to the left operand’s type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

lhs ^= rhs;

The built-in operator lhs ^= rhs computes bitwise XOR and stores the result in lhs. Each result bit is 1 when the corresponding operand bits differ, and 0 when they match. This is neither exponentiation nor a short-circuiting logical operation.

The left operand must be a modifiable lvalue of integral type; the right operand may have integral or unscoped enumeration type. The ^ computation uses integral promotions and the usual arithmetic conversions, after which the result is converted to the left operand's type. Account for width and signedness when mixing types.

Its meaning corresponds to lhs = lhs ^ rhs, except that lhs is evaluated only once. The right operand is evaluated before the left operand. The entire expression yields an lvalue referring to the modified left operand.

In the example, flags ^= mask toggles the bits marked by ones in mask: 0b1010 ^ 0b0110 produces 0b1100, or 12. Repeating the operation with the same mask restores 10. These rules describe the built-in operator.

Examples

#include <iostream>

int main() {
    unsigned int flags = 0b1010u;
    const unsigned int mask = 0b0110u;

    flags ^= mask;
    std::cout << flags << '\n';

    flags ^= mask;
    std::cout << flags << '\n';
}

Result

12
10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources