Does this function to detect complete overflow of additives really work?

While reading the comments for this question , I came across the comp.lang.c FAQ link, which shows a “thorough add function” that supposedly detects an 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 positive, then why do they do int rather than unsigned int in the first place?

+7
c ++ c integer-overflow
source share
2 answers

They probably just missed it. The sitelinks on the frequently asked questions page seem to contain more correct code.

+1
source share

The OP detected that INT_MAX - b could overflow, making the remaining code invalid for proper overflow detection. This does not work.

 if (INT_MAX - b < a) { // Invalid overflow detection 

The following describes a method for detecting overflow without UB:

 int is_undefined_add1(int a, int b) { return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a); } 

why make them int , and not unsigned int in the first place?

Switching to unsigned does not solve the problem at all. The range unsigned: [0...UINT_MAX] can be half the range int: [INT_MIN...INT_MAX] . IOWs: INT_MAX == UINT_MAX . Such systems are rare these days. IAC, mutable types are not needed, as specified in is_undefined_add1() .

+4
source share

All Articles