Karthik Kumar <kaykaydreamz_nospamplz@yahoo.com> writes:
I am writing this application that needs a lot of arithmetic
calculations. I was wondering if the GNU C++ compiler specifies any
way of detecting arithmetic overflows. ( some extensions or flags or
some options).
"The C++ Programming Language", 3rd edition, p.122:
Implementations do not have to check for arithmetic overflow and
hardly any do.
I was looking at overflow_error class provided by stdexcept
library in C++. That does not seem to be raised automatically.
Same book, p. 385, lists 'overflow_error' as being thrown *only*
from bitset<>::to_ulong().
How would I handle similar situations ?
You'll have to handle them yourself, e.g.
inline short mult(short a, short b) {
int res = a * b;
if (SHRT_MIN <= res && res <= SHRT_MAX) return res;
throw overflow_error();
}
...
short a = -10000;
short b = mult(a, 8); // now throws