There are different options and probably no one that suits every situation and need.
For example in this situation you could check that if pow
is less or equal to INT_MAX/10
before multiplying. This works because INT_MAX/10
is the largest number such that it times 10 will be at most INT_MAX
. Note that the compiler would normally precompute the INT_MAX/10
if you insert it into the code (otherwise you could put it in a local variable if it bothers you):
int y = 0;
for (int i=0; i<NUM; i++) {
int pow = 1;
for (int j=0 j<i; j++) {
if( pow > INT_MAX/10 )
throw OverflowException;
pow *= 10;
}
y+= vec[i]*pow; // where vec is a vector of digits
}
This solution has the disadvantage that if the other factor is not constant the compiler (and you) can't reasonably avoid the division INT_MAX/n
to be done at runtime (and division is normally more expensive than multiplication).
Another possibility is that you could do the calculation in a wider type. For example:
int y = 0;
for (int i=0; i<NUM; i++) {
int32_t pow = 1;
for (int j=0 j<i; j++) {
int64_t tmp = (int64_t)pow * (int64_t)10;
if( tmp > (int64_t)INT32_MAX )
raise OverflowException;
pow = (int32_t)tmp;
}
y+= vec[i]*pow; // where vec is a vector of digits
}
This have the disadvantage that first a wider type might not be available, and if it is it may require software implementation of the multiplication (for example 64-bit on 32-bit systems) which means slower multiplication.
Another situation is where you add two integers. If overflow occurs the result will be less than both integers, especially if they're both positive the result will be negative.