Catching of arithmetic overflows

Hi!

Is there a way to catch integer overflows for arithmetic operations on Arduino?
I'm sure I've seen an overflow flag somewhere in ATMega datasheet, but is there any support for this in arduino library?

There is a discussion about this here that may be of interest:

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=printview&t=41293&start=0

Is there a way to catch integer overflows for arithmetic operations on Arduino?

Yes, you can do defensive programming - which eats up all your CPU cycles - in which you test before you do the math

examples:

if (MAXINT / y > x) z = x * y;
else overflow();

if (MAXINT - y > x) z = x + y;
else overflow();

if (-MAXINT + y < x) z = x - y;
else overflow();

in fact this is often done for dividing by zero :

if (y != 0) z = x/y;
else divideByZero();

more complex functions need more complex boolean expressions ...

The best thing is to design your code so that you can show that all arithmetic operations will be in range. Typically this will involve checking that untrusted external inputs are in range before using them, and avoiding code that accumulates an unlimited number of values.

One of the services that my company provides is formal analysis of safety-critical software written in C. When we are asked to analyse software that has already been tested and put into service, the most common type of problem we find is arithmetic overflow for unusual combinations of input data.