Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
langc
#include <assert.h>
 
signed int si_a;
signed int si_b;
signed int result;

void func(void) {
  /* Initialize si_a, si_b and result */

  static_assert(
    sizeof(long long) >= 2 * sizeof(int),
    "Unable to detect overflow after multiplication"
  );

  signed long long tmp = (signed long long)si_a *
                         (signed long long)si_b;
  /*
   * If the product cannot be represented as a 32-bit integer,
   * handle as an error condition.
   */
  if ( (tmp > INT_MAX) || (tmp < INT_MIN) ) {
    /* Handle error condition */
  } else {
    result = (int)tmp;
  }
  /* ... */
}

The compliant solution uses a static assertion to ensure that the overflow detection will succeed. See DCL03-C. Use a static assertion to test the value of a constant expression for a discussion of static assertions.

...

Code Block
bgColor#ccccff
langc
#include <limits.h>
 
signed long s_a;
signed long result;

void func(void) {
  /* Initialize s_a and result*/
  if (s_a == INT_MIN) {
    /* Handle error condition */
  } else {
    result = -s_a;
  }
  /* ... */
}

Anchor
Left Shift Operator
Left Shift Operator

...