--- In [email protected], "Pete Calvert" <[EMAIL PROTECTED]> wrote:
>
> All,
>
> I'm trying to think of a way of preventing numeric
> overflow in C++, for example:
>
> int a, b;
> ...
> int c = a*b;
> ...
>
> How can I guarentee that c will have the correct
> value, or report an error if overflow will occur.
> I know that always using a variable that has a
> greater range for the result, but I don't think
> that is possible in this instance, so does anyone
> know another way?
Use a check like this: {C syntax}
#include <limits.h>
...
if (MAXINT / a > b)
{ c = a * b;
/* here you are safe. */
...
}
else
{ perror( "a * b would overflow!);
exit( EXIT_FAILURE);
}
The name MAXINT is wrong, but currently I don't have a Unix system to
look it up; search the header file limits.h, you will find many
constants there.
Regards,
Nico