I thought this was going to be about efficient overflow checking at a USER level. I want to be able to write efficient code something like
bool SafeAddInts(int a, int b, int* out) {
if (willOverFlowAdd(a,b)) {
return false;
}
*out = a + b;
return true;
}
Or better
bool SafeAddInts(int a, int b, int* out) {
int temp = a + b;
if (magicCheckProcessorFlagsForOverflow()) {
return false;
}
*out = temp;
return true;
}
Or something along those lines.
It's all great the compiler can maybe generate code that crashes my program there's overflow but what's the efficient case for handling it at a user level given that overflow is undefined in the general case given the result is undefined?
GCC[1] and Clang[2] both support this with __builtin_add_overflow and family:
int a = get_number_a(), b = get_number_b(), c;
if (__builtin_add_overflow(a, b, &c)) // Note: Unlike your example, returns true iff overflow occurred
uh_oh();
else
everything_is_ok();
These are quite efficient on many common architectures.
MSVC has SafeInt[3] which is more awkward but gets the job done.
That'll badly pollute your control flow graph though. You'll have a branch and a later merge for every SafeAddInts you do. Implicit handling of overflow with some kind of trap avoid this.
It's no worse than checking return codes though. And I really don't want integer overflow check to be turned on for all integers. I'm writing stuff that has to run, even if it occasionally produces a wrong answer. Having hidden checks inserted by the compiler that just crash the program would be really bad. Yes, I should check the inputs, but if I ever forget to check one, it's better that some ranges of input data produce nonsense results rather than crashes.
It's all great the compiler can maybe generate code that crashes my program there's overflow but what's the efficient case for handling it at a user level given that overflow is undefined in the general case given the result is undefined?