How can I ensure that integer arithmetic doesnt overflow?

Q

How can I ensure that integer arithmetic doesnt overflow?

✍: Guest

A

The usual approach is to test the operands against the limits in the header file <limits.h> before doing the operation. For example, here is a ``careful'' addition function:

int
chkadd(int a, int b)
{
if(INT_MAX - b < a) {
fputs("int overflow\n", stderr);
return INT_MAX;
}
return a + b;
}

2015-03-04, 1177👍, 0💬