While reading the comments for this question, I came across a link to the comp.lang.c FAQ that shows a "careful addition function" which purportedly detects integer overflow:
int
chkadd(int a, int b)
{
if (INT_MAX - b < a) {
fputs("int overflow\n", stderr);
return INT_MAX;
}
return a + b;
}
How does this not overflow if b == -1? If the assumption is that a and b are both positive, why make them int rather than unsigned int in the first place?
INT_MAX - (-1)equalsINT_MIN?intmight wrap: but it is undefined behaviour.aandbare positive. Useful for converting strings tointwhile checking for overflow.INT_MAX - (-1)is undefined behavior. A compiler can optimize that code to any answer includingINT_MIN, 0, or 42and still be a compliant compiler.