...
Code Block |
---|
signed int result; signed int si1 = INT_MIN; signed int si2 = 2; signed long long tmp = (signed long long)lhs * (signed long long)rhs; if ( (tmp > INT_MAX) || (tmp < INT_MIN)) { /* The product cannot fit in a 32-bit int */ error_handler("OVERFLOW ERROR", NULL, EOVERFLOW); } result = (int)tmp; |
It is important to note that the above code is only compliant on systems where long long
is atleast at least twice the size of int
. On systems where this does not hold the following compliant solution may be used to ensure signed overflow does not occur.
Code Block |
---|
signed int result; signed int si1 = INT_MIN; signed int si2 = 2; if (si1 si1>> 0){ if (si2 si2>> 0) { if(si1> if (si1 > (INT_MAX / si2)) { error_handler("OVERFLOW ERROR", NULL, EOVERFLOW); } } else { if (si2 si2<< (INT_MIN / si1)) { error_handler("OVERFLOW ERROR", NULL, EOVERFLOW); } } } else { if (si2 > 0) { if( if (si1 < (INT_MIN / si2)) { error_handler("OVERFLOW ERROR", NULL, EOVERFLOW); } } } else { if( (si1 != 0) && (si2 < (INT_MAX / si1))) { error_handler("OVERFLOW ERROR", NULL, EOVERFLOW); } } } result = si1 * si2; |
Division
...