Am I the only one who thinks that writing
if (x + y < x)
is utterly insane? It completely breaks the abstraction of algebra that's being used in the language. Much better would be: if (ADDITION_WOULD_OVERFLOW_INT(x, y))
{
...
}
This is (a) far easier to read, and (b) more likely to be more correctly implemented as something like: #define ADDITION_WOULD_OVERFLOW_INT(a, b) \
(((a) > 0 && (b) > 0 && (b) > INT_MAX - (a)) || \
((a) < 0 && (b) < 0 && (b) < INT_MIN - (a)))
For bonus points you could write this as part of the compiler support library to derive the types and limits automatically, or even define it as part of the compiler. Why do GCC/clang not have: __builtin_addition_would_overflow(a, b)
?