Main Content

Bitwise and arithmetic operations on the same data

Statement with mixed bitwise and arithmetic operations

Description

This defect occurs when bitwise and arithmetic operations are performed in the same expression.

Risk

Mixed bitwise and arithmetic operations do compile. However, the size of integer types affects the result of these mixed operations. For instance, the arithmetic equivalent of a left shift (<<) by a certain number of bits depends on the number of bits in the variable being shifted and therefore on the internal representation of its data type. With a mix of bitwise and arithmetic operations, the same expression can produce different results on different targets.

Mixed operations also reduce readability and maintainability.

Fix

Separate bitwise and arithmetic operations, or use only one type of operation per statement.

Examples

expand all

unsigned int bitwisearithmix()
{
    unsigned int var = 50;
    var += (var << 2) + 1;
    return var;
}

This example shows bitwise and arithmetic operations on the variable var. var is shifted by two (bitwise), then increased by 1 and added to itself (arithmetic).

Correction — Arithmetic Operations Only

You can reduce this expression to arithmetic-only operations: var + (var << 2) is equivalent to var * 5.

unsigned int bitwisearithmix()
{
    unsigned int var = 50;
    var = var * 5 +1;
    return var;
}

Result Information

Group: Good Practice
Language: C | C++
Default: Off
Command-Line Syntax: BITWISE_ARITH_MIX
Impact: Low

Version History

Introduced in R2016b