Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-INT34-C_a

In this section:
Synopsis

Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand.

Enabled by default

Yes

Severity/Certainty

Low/Low

lowlow.png
Full description

Bitwise shifts include left-shift operations of the form shift-expression << additive-expression and right-shift operations of the form shift-expression >> additive-expression. The standard integer promotions are first performed on the operands, each of which has an integer type. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. Do not shift an expression by a negative number of bits or by a number greater than or equal to the precision of the promoted left operand.

Coding standards
CERT INT34-C

Do not shift a negative number of bits or more bits than exist in the operand

Code examples

The following code example fails the check and will give a warning:

#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

void func(signed long si_a, signed long si_b) {
  signed long result;
  if (si_a > (LONG_MAX >> si_b)) {
    /* Handle error */
  } else {
    result = si_a << si_b;
  }
  /* ... */
}

The following code example passes the check and will not give a warning about this issue:

#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

extern size_t popcount(uintmax_t);
#define PRECISION(x) popcount(x)

void func(signed long si_a, signed long si_b) {
  signed long result;
  if ((si_a < 0) || (si_b < 0) ||
      (si_b >= PRECISION(ULONG_MAX)) ||
      (si_a > (LONG_MAX >> si_b))) {
    /* Handle error */
  } else {
    result = si_a << si_b;
  }
  /* ... */
}