>> - right shift

suggest change
#include <iostream>

int main() {
    const int a = 2;      // 0010b
    const int b = a >> 1; // 0001b
    
    std::cout << "a = " << a << ", b = " << b << '\n';
}
a = 2, b = 1

Why

The bitwise right-shift operator shifts the left operand right by the number of positions given by the right operand. For an unsigned value, zeros are shifted in from the left. Since C++20, right-shifting a negative signed value performs an arithmetic right shift, rounding the quotient toward negative infinity. In earlier standards, the result for a negative signed value was implementation-defined.

int a = -2;    
int b = a >> 1; // -1 since C++20; implementation-defined before C++20

The behavior is undefined if the shift count is negative or is greater than or equal to the number of bits in the promoted left operand:

int a = 1;
int b = a >> -1;  // undefined behavior

The bitwise right-shift operator does not modify its operands. The compound assignment operator >>= stores the result in its left operand:

#include <iostream>

int main() {
    int a = 2;  // 0010b
    a >>= 1;    // a = a >> 1;

    std::cout << "a = " << a << '\n';
}
a = 1

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents