Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Restored << CS

...

This compliant solution eliminates the possibility of overflow resulting from a left-shift operation:

Code Block
bgColor#ccccff
langc
#include <limits.h>

 
signed long s_a;
signed long result;

void func(void) {
  if ((si1 < 0) || (si2 < 0) ||
      (si2 >= sizeof(int)*CHAR_BIT) ||
      (si1 > (INT_MAX >> si2))) {
    /* handle error condition */
  } else {
    sresult = si1 << si2;
  }


  /* ... */
}

Anchor
Left Shift Operator
Left Shift Operator

This solution is also compliant with INT34-C. Do not shift a negative number of bits or more bits than exist in the operand. However, a platform in which integers have some padding bits (that are not used to represent the integer's value) can have some some bits in si1 shifted in to the padding bits.

Atomic Integers

The C Standard defines the behavior of arithmetic on atomic signed integer types to use two's complement representation with silent wraparound on overflow; there are no undefined results. However, although defined, these results may be unexpected and therefore carry similar risks to unsigned integer wrapping (see INT30-C. Ensure that unsigned integer operations do not wrap). Consequently, signed integer overflow of atomic integer types should also be prevented or detected. 

...