...
This compliant solution guarantees there is no possibility of signed overflow on systems where long long
is at least twice the size of int
.
Code Block | ||
---|---|---|
| ||
signed int si1, si2, result;
static_assert(sizeof(long long) >= 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 */
}
result = (int)tmp;
|
The compliant solution uses a static assertion to ensure that the overflow detection will succeed. See DCL03-A. Use a static assertion to test the value of a constant expression for a discussion of static assertions.
preceding code is compliant only on systems where long long
is at least twice the size of int
. On systems where this relationship does not exist, the following compliant solution may be used to ensure signed overflow does not occur.
...