Main Content

MISRA C++:2023 Rule 7.0.4

The operands of bitwise operators and shift operators shall be appropriate

Since R2024b

Description

Rule Definition

The operands of bitwise operators and shift operators shall be appropriate.

Rationale

Performing bitwise and shift operations on signed operands can result in implementation-defined behavior. For example, these operations can cause undefined or implementation-defined behavior:

  • Shifting a right operand value that is greater than or equal to the size in bits of the promoted type of the left operand

  • Shifting by a negative value

  • Left shifting a signed operand

  • Right shifting a negative value

Use unsigned operands when performing bitwise and shift operations because the result of the operation is defined when the sign bit is unaffected.

Polyspace Implementation

The rule checker reports a violation when you perform bitwise or shift operations on signed operands.

As an exception, the left operand of a shift operator can be a nonnegative constant expression of a signed integer type T before any integer promotion takes place, under these conditions:

  1. The type T must use two's complement representation for signed integers.

  2. The right operand must be a constant expression.

  3. The value of the right operand must be within a specific range: from 0 up to, but not including, the total number of bits in the type T.

  4. When performing the shift operation, none of the set bits in the left operand should be shifted into the position of the most significant bit or beyond it.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

int example1() {
    int signedOperand = -10; 
    int result = ~signedOperand;               //Noncompliant
}

int example2() {
    const int leftOperand = 1; 
    const int rightOperand = 4;
    int result = leftOperand << rightOperand;  //Compliant
}

In this example:

  • example1() attempts the NOT bitwise operation on a negative value, which is noncompliant because it causes implementation-defined behavior.

  • example2() attempts a left shift operation on a nonnegative constant which is compliant because it meets all the requirements for the exception for this rule. The left operand is a nonnegative constant expression of type int, the right operand is a constant expression within the acceptable range of a 32-bit integer (0—31), and the left shift operation does not shift any set bits into or beyond the position of the most significant bit.

Check Information

Group: Standard Conversions
Category: Required

Version History

Introduced in R2024b