Versions Compared

Key

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

...

This compliant solution works only on architectures that use two's complement representation. While most modern platforms use two's complement representation, it is best not to introduce unnecessary platform dependencies (see MSC14-C. Do not introduce unnecessary platform dependencies). This solution can also be more expensive than a post-condition test, especially on RISC CPUs.

Compliant Solution (

...

For addition and subtraction of signed integers using two's-compliment representation in which both operands have like signs, a change of sign in the result indicates an overflow condition. If the signs of the operands are different there can be no overflow.

This compliant solution performs a post-condition test following the addition operation to detect if an overflow occurred, assuming two's complement representation and the absence of traps.

Code Block
bgColor#ccccff

signed int si1, si2, sum;

/* Initialize si1 and si2 */

sum = si1 + si2;
if ((si1 > 0 && sum < 0) || (si1 < 0 && sum > 0)) {
  /* handle error condition */
} 

This compliant solution works only on architectures that use two's complement representation. While most modern platforms use two's complement representation, it is best not to introduce unnecessary platform dependencies (see MSC14-C. Do not introduce unnecessary platform dependencies).

This compliant solution also depends on undefined behavior (see MSC15-C. Do not depend on undefined behavior). Conforming implementations are free to perform any action in the presence of undefined behavior, including trapping. If the addition operation traps, it may not be possible to handle the error in the preferred application-defined manner. Also, a compiler has the license to eliminate any code that depends on the presence of undefined behavior, so it is possible that a compiler will optimize out the entire if statement containing the overflow test.

Compliant Solution (General)

This compliant solution tests the suspect addition operation to ensure no overflow occurs regardless of representation.

...