prev up next   top/contents search

comp.lang.c FAQ list · Question 20.6b

Q: How can I ensure that integer arithmetic doesn't overflow?


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;
}
See also question 19.39.

Additional links: more sample code


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North