Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Bitwise OR assignment operator (|=)

The |= operator computes the bitwise inclusive OR of the left operand's current value and the right operand, then stores the result in the left operand. One common use is setting the bits selected by a mask.

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

Syntax

lhs |= rhs

lhs |= rhs combines | with assignment. Each result bit is 1 if at least one corresponding operand bit is 1. A mask therefore sets selected bits without clearing other bits in the common computation type.

For the built-in operator, lhs must be a modifiable lvalue of integral type, and rhs must have integral or unscoped enumeration type. The | computation applies the usual arithmetic conversions, including integral promotions; the result is then converted to the type of lhs. A narrower destination type can lose some bits.

The meaning corresponds to lhs = lhs | rhs, except that the expression lhs is evaluated only once. The entire expression produces an lvalue referring to the modified left operand. These rules describe the built-in operator.

In the example, flags initially holds 0b0101u, and mask holds 0b0010u. After flags |= mask, the value is 0b0111u, or decimal 7.

Examples

#include <iostream>

int main() {
    unsigned int flags = 0b0101u;
    constexpr unsigned int mask = 0b0010u;
    flags |= mask;
    std::cout << flags << '\n';
}

Result

7

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