Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Bitwise OR operator |

The | operator combines corresponding bits of two values: a result bit is 1 when at least one input bit is 1. It is useful for combining flag masks and is distinct from the logical || operator.

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

Syntax

lhs | rhs

The built-in | operator performs bitwise inclusive OR: at each bit position, it produces 0 only when both bits are 0. Otherwise it produces 1, including when both bits are 1. For example, 0b0100u | 0b0010u produces 0b0110u, which is 6.

Operands must have integral or unscoped enumeration types. Built-in | does not directly accept enum class values. It applies the usual arithmetic conversions, including integral promotions; the common converted type is the result type. Consequently, the result need not retain an operand's narrow type. Prefer matching unsigned types for simple masks.

Do not confuse | with ||: built-in || returns bool and skips its right operand if the left operand is true. Built-in | evaluates both operands and does not guarantee left-to-right evaluation. Its left associativity means that a | b | c groups as (a | b) | c, not that evaluation happens in that order.

The expression a | b alone does not modify a or b. To store the combined bits, use assignment or a |= b; the latter corresponds to a = a | b but evaluates the left operand only once. bitor is an alternative spelling of |, whereas or means ||.

The example combines the read and write flags into permissions and prints 6. The static_assert checks the expected value during compilation. This explanation covers the built-in operator, not class overloads. The material targets C++23; the supplied document is an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    constexpr unsigned int read = 0b0100u;
    constexpr unsigned int write = 0b0010u;
    constexpr unsigned int permissions = read | write;
    static_assert(permissions == 0b0110u);
    std::cout << permissions << '\n';
}

Result

6

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