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:
The type
T
must use two's complement representation for signed integers.The right operand must be a constant expression.
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
.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
Check Information
Group: Standard Conversions |
Category: Required |
Version History
Introduced in R2024b