Main Content

MISRA C++:2008 Rule 5-0-21

Bitwise operators shall only be applied to operands of unsigned underlying type

Description

Rule Definition

Bitwise operators shall only be applied to operands of unsigned underlying type.

Rationale

Bitwise operations are not meaningful when they are applied to signed operands. Applying bitwise operations to signed operands might result in an unexpected and implementation dependent result. For instance, if you right shift a negative number, the result varies depending on your environment. Avoid using bitwise operations on signed operands.

Polyspace Implementation

Polyspace® raises a violation of this rule when you apply a bitwise operation on a signed operand or expression.

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

typedef signed   short        int16_t;
typedef unsigned short        uint16_t;

void foo(uint16_t ua, uint16_t ub, int16_t a)
{
	if   (   ( ua & a ) == 0x1234U ) {}        // Noncompliant
	if   (   ( ua | ub ) == 0x1234U ) {}       // Compliant
	if   (   ~a == 0x1234U ) {}                // Noncompliant
	if   (   ~ua == 0x1234U ) {}               // Compliant
}

In this example, Polyspace flags the use of bitwise operations on signed operand a. Bitwise operations that involve unsigned operands such as ua, ub, and the hexadecimal number 0x1234U, are compliant with this rule.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b