mickadoo mickadoo - 18 days ago 5
C Question

Bitshift on assignment has no effect on the variable

I thought I'd found something similar in this answer but in that case they weren't assigning the result of the expression to the variable. In my case I am assigning it but the bitshift part of the expression has no effect.

unsigned leftmost1 = ((~0)>>20);
printf("leftmost1 %u\n", leftmost1);


Returns

leftmost1 4294967295


Whereas

unsigned leftmost1 = ~0;
leftmost1 = leftmost1 >> 20;
printf("leftmost1 %u\n", leftmost1);


Gives me

leftmost1 4095


I would expect separating the logic into two lines would have no impact, why are the results different?

Answer

In the first case, you are doing a signed right shift, because ~0 results in a signed value. The exact behavior of signed right shifts is implementation-defined, but most platforms, including yours, extend the sign bit, so the shift is a no-op for your input of "all ones".

In the second case, you are doing an unsigned right shift, since leftmost1 is an unsigned value. So you shift in zeros from the left.

If you wanted to do an unsigned shift without the intermediate assignmetn, you can do:

(~0u) >> 20

Where the u suffix indicates an unsigned literal.

Comments