int a;
// lots of code
int b = a + 1;
// check for overflow
if (b <= a)
abort();
the compiler is allowed to remove the check because in the absence of UB a + 1 > a, therefore the conditional is always false. int a;
// lots of code
int b = a + 1;
// check for overflow
if (b <= a)
abort();
the compiler is allowed to remove the check because in the absence of UB a + 1 > a, therefore the conditional is always false.In that case, something like: [...] if (a > INT_MAX - 1) abort(); int b = a + 1; [...]
Much easier said than done:
https://github.com/postgres/postgres/blob/master/src/include...
Yeah, a standard library function that does this would be good. But many people would just use * instead of this function, and so the problem would partially remain.
In c++ it would be a little simpler due to templates, so the types of the arguments to the function can be derived. But the type of the result can still confuse programmers. Although maybe it's not so bad, because an overflow that happens during multiplication (or other math operations) is undefined-behavior, but an overflow that happens during assignment of the multiplication result to a variable that can't hold it is only implementation-defined behavior, not undefined behavior.