MISRA C++:2023 Rule 7.0.4
The operands of bitwise operators and shift operators shall be appropriate
Since R2024b
Description
The operands of bitwise operators and shift operators shall be appropriate. 1
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, violations are not reported on a signed left operand of a shift operation if all of these conditions are met:
The signed left operand is a nonnegative constant expression.
The type of the signed left operand before integral promotion (
T) uses two's complement representation.The right operand of the shift operator a constant expression with minimum value of 0 and a maximum value of one less than the number of bits in T (
0.. sizeof(T)*CHAR_BIT-1).The shift operation does not shift into or beyond the most significant bit or the sign bit.
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 |
PQL Name: std.misra_cpp_2023.R7_0_4 |
Version History
Introduced in R2024b1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.