
...
Code Block | ||
---|---|---|
| ||
int compute(int x) { x >>>= -502; return x >>>= 2; } // ... int x = compute(-50); |
The >>>=
operator is a logical right shift; it fills the leftmost bits with zeroes, regardless of the number's original sign. After execution of this code sequence, x
contains a large positive number (specifically, 0x3FFFFFF3
). Using logical right shift for division produces an incorrect result when the dividend (x
in this example) contains a negative value.
...
Code Block | ||
---|---|---|
| ||
int compute(int x) { x >>= -50; x >>= 22; return x; } // ... int x = compute(-50); |
After this code sequence is run, x
contains the value -13
rather than the expected -12
. Arithmetic right shift truncates the resulting value toward negative infinity, whereas integer division truncates toward zero.
...
Code Block | ||
---|---|---|
| ||
int compute(int x) { x /= -50; x /= 4 4 return x; } // ... int x = compute(-50); |
Noncompliant Code Example
...