>>= is the right shift assignment operator. The expression x >>= n shifts the bits of x right by n places and stores the result back in x. It is shorthand for x = x >> n.
How the symbol is built
The operator combines the right shift >> with the assignment =. Written together, with no space between them, they form the single token >>=. Its counterpart is <<=, the left shift assignment, which works the same way in the other direction. Like the other C assignment operators, such as +=, it changes the variable on its left.
Worked examples
#include <stdio.h>
int main(void) {
int x = 16; /* binary 10000 */
x >>= 2; /* same as x = x >> 2 */
printf("%d\n", x);
return 0;
}
Output:
4
Here are a few more starting values:
Starting x |
Statement | New x |
What happened |
|---|---|---|---|
16 (10000) |
x >>= 2 |
4 (00100) |
Shifted right two places |
9 (1001) |
x >>= 1 |
4 (0100) |
The lowest bit, 1, fell off |
40 (101000) |
x >>= 3 |
5 (101) |
Shifted right three places |
How right shift treats the bits
Each bit moves down by n places, and bits that fall off the bottom are discarded. What fills the empty places at the top depends on the type:
- For unsigned types, zeros always fill the top. That makes
>>=predictable for bit work. For example,mask >>= 4turns0xF0into0x0F. - For negative signed values, the result is implementation-defined in C and in C++ before C++20. Most compilers copy the sign bit into the empty places, so a variable holding -8 becomes -4 after
x >>= 1.
Don’t rely on >>= to divide a negative number. Division rounds toward zero, so -7 / 2 gives -3, while -7 >> 1 gives -4 on most compilers.
Same as x = x >> n, with one difference
For a built-in type, x >>= n and x = x >> n produce the same value. The difference is that x >>= n evaluates the left operand only once. This matters when the left operand has a side effect. For example, values[next()] >>= 1 calls next() one time, but values[next()] = values[next()] >> 1 calls it twice.
Limits
- Shifts work only on integer types.
>>=does not apply tofloatordouble. - The shift count must be zero or more and less than the width of the promoted left operand. Otherwise the result is undefined. On a platform where
intis 32 bits,x >>= 32is undefined. - The same rules apply to
<<=.
In short, >>= is a right shift that updates its variable. Use it when the shifted value should replace the original. Use the plain >> when you need the shifted value inside a larger expression.