Versions Compared

Key

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

...

This noncompliant code example uses the complement operator in the test for unsigned integer overflow. It assumes both numbers are nonnegative:

Code Block
bgColor#FFCCCC
langc
unsignedsigned int uisi;
unsignedsigned int ui2si2;
unsignedsigned int sum;

if (si < 0 || si2 < 0) {
  /* Handle error condition */
}
if (~ui~si < ui2si2) {
  /* Handle error condition */
}
sum = uisi + ui2si2;

This code assumes that the implementation uses two's complement representation. This assumption is commonly true but is not guaranteed by the standard.

...

This compliant solution implements a strictly conforming test for unsigned overflow:

Code Block
bgColor#ccccff
langc
unsigned int uisi;
unsigned int ui2si2;
unsigned int sum;

if (UINTsi < 0 || si2 < 0) {
  /* Handle error condition */
}
if (INT_MAX - uisi < ui2si2) {
  /* Handle error condition */
}
sum = uisi + ui2si2;

If the noncompliant form of this test is truly faster, talk to your compiler vendor because, if these tests are equivalent, optimization should occur. If both forms have the same performance, prefer the portable form.

...