2
SolunacIn turn, my English is very bad but I hope that You will understand me.
Цитата:
So, how can we check for leaving the admissible range of the chosen data type in temporary results?
I think You have a few options. For example, You can rearrange your formula so that all the temporary values fall in some bounded range and therefore don't cause overflow. Imagine a ratio of two factorials, say; each factorial can achieve astronomical values but the ratio itself is equal to some relatively small number. Is it your case?
Another option is to predict the overflow in advance by analyzing differences between your values and the capacity of selected datatype. Let You have two (integer) variables
int A and
int B. How can you predict the overflow in the "enlarging" operation such as addition? Obviously, instead of writing absurd like
try {int C=A+B;} catch(...) {} all that you need is to compare value of
A to the largest possible value of type
int and then compare this difference to the value of your second variable
B (in other words, you need check whether current datatype provide enough room to contain additional data or not,) i.e. you can write something like
bool OverflowFlag = (MAXINT-A) < B. (Of course, this example must be extended to handle signed numbers.)
Finally, it's possible to provide variables of some larger datatype, especially for temporary results. E.g. even if your function is just a map from
int to
int, You can define local variables as, say,
long long int. :)
May be, in some cases, it's make sense to check the state of your hardware directly. I mean checking some specific hardware flags or something similar. But it's far from C++. :)