Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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.

...

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

Compliant Solution

Changing the second line to reflect the arithmetic nature of x causes the programmer's intentions to become clearer.

...

A reviewer might now know that the operation should be checked for integer overflow. This might not have been apparent in the original code listing.

Compliant Practice

In order to further separate bitfields and numeric types, it might be prudent to define a bitfield type. A programmer can then run automated tools over the code in question to verify that only bit manipulations are performed on variables of this type.

Code Block
bgColor#ccccff
typedef int bitfield;
bitfield x = 0x7f3;
x = (x << 2) | 3; /* shifts in two 1-bits from the right */

Risk Assessment

By complicating information regarding how a variable is used in code, it is difficult to determine which checks must be performed to ensure data validity. Explicitly stating how a variable is used determines which checks to perform.

...