You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Avoid performing bit manipulation and arithmetic operations on the same variable. Though such operations are valid and will compile, they can lead to lesser code readability. Specifically declaring a variable as containing a numeric value or a bitfield makes the programmer's intentions clearer and can lead to better code maintainability.

Non-Compliant Coding Example

In this non-compliant example, both bit manipulation and arithmetic manipulation is performed on the integer type x. The end result is an optimized line of code
that changes x to 5x + 1.

int x = 50;
x += (x << 2) + 1;

This is a legal manipulation that in two's-complement representation and discounting overflow multiplies x by 5, then increments it by 1. Because the operation uses bit-shifting rather than multiplication, it performs faster on some processor types that do not have efficient integer multiplication datapaths.

Unfortunately, it is challenging to immediately understand the effect of the second line of code. The code is not self-documenting.

Compliant Coding Example

  • No labels