Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Right-shift assignment operator (>>=)

The >>= operator shifts the left operand's bits to the right and stores the result in the same object. The left operand is evaluated only once. Validity depends on the shift count and the type after integral promotion.

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

Syntax

lhs >>= rhs

The built-in >>= operator combines right shift with assignment. lhs >>= rhs behaves like lhs = lhs >> rhs, but evaluates lhs only once. The left operand must be a modifiable lvalue of integral type, such as a non-const variable; the right operand must have integral or unscoped enumeration type. The expression's result is an lvalue referring to the modified left operand.

Integral promotions take place before the shift; the shift result is then converted to the left operand's type and stored. The shift count must be nonnegative and smaller than the width of the promoted left operand's type. Violating this condition causes undefined behavior, rather than automatically limiting the shift count.

In C++23, right shift corresponds to division by a power of two, rounded toward negative infinity. Signed shifts preserve the sign: -9 >> 1 yields -5, unlike -9 / 2, which yields -4. For unsigned values, vacated positions are filled with zeros. Plain >> does not store its result in the left operand; >>= does.

This description covers the built-in operator. The supplied website hosts an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    unsigned int value = 40u;
    value >>= 3;

    int negative = -9;
    negative >>= 1;

    std::cout << value << '\n' << negative << '\n';
}

Result

5
-5

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