...
In this non-compliant code example, the programmer attempts to (prematurely) optimize dividing x by 4optimize a division by four operation by shifting right by two.
| Code Block | ||
|---|---|---|
| ||
int x = -50; x >>= 2; |
Although this code is likely to perform a the division by 4 correctly, it is not guaranteed to. If x has a signed type and a negative value, the operation is implementation defined and could be implemented as either an arithmetic shift or a logical shift. In the event of a logical shift, if the integer is represented in either one's complement or two's complement form, the most significant bit (which controls the sign in a different way for both representations) will be set to zero. This will cause a once negative number to become a possibly very large positive number.
For example, if the internal representation of x is 0xFFFF FFCE (two's complement), an arithmetic shift results in 0xFFFF FFF3 (-13 in two's complement), while a logical shift results in 0x3FFF FFF3 (1 073 741 811 in two's complement).The result of the shift also depends on the underlying representation of the integer type.
Compliant Solution 2
In this compliant solution, the shift is replaced by a division operation so that the intention is clear.
...