...
Code Block |
---|
|
signed int si1, si2, sum;
/* Initialize si1 and si2 */
if (((si1>0) && (si2>0) && (si1 > (INT_MAX-si2)))
|| ((si1<0) && (si2<0) && (si1 < (INT_MIN-si2)))) {
/* handle error condition */
}
else {
sum = si1 + si2;
}
|
...
Code Block |
---|
|
signed int si1, si2, result;
/* Initialize si1 and si2 */
if (((si1^si2)
& (((si1 ^ ((si1^si2)
& (1 << (sizeof(int)*CHAR_BIT-1))))-si2)^si2)) < 0) {
/* handle error condition */
}
else {
result = si1 -si2)^si2)) < 0) si2;
}
|
This compliant solution only works 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 recommendation MSC14-C. Do not introduce unnecessary platform dependencies.)
Compliant Solution (General)
This compliant solution tests the operands of the subtraction to guarantee there is no possibility of signed overflow, regardless of representation.
Code Block |
---|
|
signed int si1, si2, result;
/* Initialize si1 and si2 */
if ((si2 > 0 && si1 < INT_MIN + si2) ||
(si2 < 0 && si1 > INT_MAX + si2)) {
/* handle error condition */
}
else {
result = si1 - si2;
}
|
...
Anchor |
---|
| Multiplication |
---|
| Multiplication |
---|
|
...
Code Block |
---|
|
signed int si1, si2, result;
/* Initialize si1 and si2 */
static_assert(
sizeof(long long) >= 2 * sizeof(int),
"Unable to detect overflow after multiplication"
);
signed long long tmp = (signed long long)si1 *
(signed long long)si2;
/*
* 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;
}
|
...
Code Block |
---|
|
signed int si1, result;
/* Initialize si1 */
if (si1 == INT_MIN) {
/* handle error condition */
}
else
result = -si1;
}
|
Anchor |
---|
| Left Shift Operator |
---|
| Left Shift Operator |
---|
|
...
Code Block |
---|
|
int si1, si2, sresult;
/* Initialize si1 and si2 */
if ( (si1 < 0) || (si2 < 0) ||
(si2 >= sizeof(int)*CHAR_BIT) ||
(si1 > (INT_MAX >> si2))
) {
/* handle error condition */
}
else {
sresult = si1 << si2;
}
|
...