Main Content

MISRA C++:2008 Rule 5-8-1

The right hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left hand operand

Description

Rule Definition

The right hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left hand operand.

Rationale

When you use a shift operator, the value of the right-hand operand must be:

  • Greater than or equal to zero.

  • Less than the bit size of the data type of the left-hand operand.

If the above is not true, using a shift operator results in undefined behavior, which makes your program unpredictable and yields unexpected results.

Polyspace Implementation

Polyspace® reports a rule violation when you use a negative operand on the right-hand side of a shift operator. Polyspace also reports a violation when the right-hand side of a shift operator is at least as large as the bit size of the data type of the left-hand 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

expand all

int shifted_output (int val) {
    if (val < 3) { 
        return val<<3; //Compliant
    }
    
    if (val > 3) { 
        return val>>-1; //Noncompliant
    } 
    
    return val<<33; //Noncompliant
}

In this example, the right-hand side of the shift operator in the first if statement is less than the size of int and greater than zero, so Polyspace does not report a violation. Because the right-hand operand of the shift operator is negative in the second if statement and greater than the size of int in the third, Polyspace reports a rule violation.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b