...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h>
signed int si_a;
signed int si_b;
signed int sum;
void func(void) {
/* Initialize si_a, si_b and sum*/
if ( ((si_a^si_b) | (((si_a^(~(si_a^si_b) & INT_MIN)) + si_b)^si_b)) >= 0) {
/* Handle error condition */
} else {
sum = si_a + si_b;
}
/* ... */
} |
This compliant solution works only on architectures that use two's complement representation. Although 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 postcondition test, especially on RISC CPUs.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h>
signed int si_a;
signed int si_b;
signed int sum;
void (func) {
/* Initialize si_a, si_b and sum */
if (((si_b > 0) && (si_a > (INT_MAX - si_b)))
|| ((si_b < 0) && (si_a < (INT_MIN - si_b)))) {
/* Handle error condition */
} else {
sum = si_a + si_b;
}
/* ... */
} |
This solution is more readable but may be less efficient than the solution that is specific to two's complement representation.
...