...
In this noncompliant code example, both bit manipulation and arithmetic manipulation are performed on the integer x. The result is a (prematurely) optimized statement that assigns 5x + 1 to x for implementations, where integers are represented as two's complement values.
| Code Block | ||||
|---|---|---|---|---|
| ||||
unsigned int x = 50; x += (x << 2) + 1; |
...
In this compliant solution, the assignment statement is modified to reflect the arithmetic nature of x, resulting in a clearer indication of the programmer's intentions.
| Code Block | ||||
|---|---|---|---|---|
| ||||
unsigned int x = 50; x = 5 * x + 1; |
...
In this noncompliant code example, the programmer prematurely optimizes code by replacing a division with a right shift.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int x = -50; x >>= 2; |
Although this code is likely to perform the division correctly, it is not guaranteed to. If x has a signed type and a negative value, the operation is implementation defined and can 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 for both representations) will be set to zero. This will cause a once negative number to become a possibly very large, positive number. For more details, see recommendation INT13-C. Use bitwise operators only on unsigned operands.
...
In this compliant solution, the right shift is replaced by division.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int x = -50; x /= 4; |
The resulting value is now more likely to be consistent with the programmer's expectations.
...