MISRA C++:2008 Rule 5-0-10
If the bitwise operators ~ and << are applied to an operand with an underlying type of unsigned char or unsigned short, the result shall be immediately cast to the underlying type of the operand
Description
Rule Definition
If the bitwise operators ~ and << are applied to an operand with an underlying type of unsigned char or unsigned short, the result shall be immediately cast to the underlying type of the operand.
Rationale
When the bitwise operators ~
and <<
are
applied to small integer types, such as unsigned short and unsigned char, the operations are
preceded by integral promotion. That is, the small integer types are first promoted to a
larger integer type, and then the operation takes place. The result of these bitwise
operation might contain unexpected higher order bits. For
instance:
uint8_t var = 0x5aU; uint8_t result = (~var)>>4;
var
is 0101 1010
and that of
~var
is 1010 0101
. You might expect that
result
is 0000 1010
. Because var
is promoted to a larger integer before ~var
is calculated, result becomes
1111 1010
. The higher order bits might be unexpected. The results of
such operations might depend on the size of int
in your
implementation.To avoid confusion and unexpected errors, cast the result of the bitwise
~
and >>
operators back to the underlying type of
the operands before using the results. For
instance:
uint8_t var = 0x5aU; uint8_t result = (static_cat<unit8_t>(~var))>>4;
result
in this case is 0000
1010
, which is the expected value.As an exception, casting is not required if you apply these bitwise operators on short
integer types, and then immediately assign the result to an object of the same underlying
type. For instance, the value of result in this case is 0000 1010
without
requiring a
cast.
uint8_t var = 0x5aU; unit8_t result = ~var; // No higher order bits // due to implicit conversion uint8_t result = results>>4;
Polyspace Implementation
Polyspace® flags the use of the bitwise ~
and >>
operators if all of these conditions are true:
The operators are used on an
unsigned short
orunsigned char
operand.The result of the operation is not immediately assigned to an object that has the same underlying type as the operand.
The result is used without being cast to the underlying type of the operand.
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: Expressions |
Category: Required |
Version History
Introduced in R2013b