3 ms·
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
by greggman 11y ago
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?
- dbaupp 11y agoYou may be interested in http://blog.regehr.org/archives/1139 http://blog.regehr.org/archives/1139 by the same author, and also the (GNU) compiler built-ins for exactly that task https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins... . (Note that your second example can't work in C/C++, since the check happens after the operation.)
- daurnimator 11y ago> (Note that your second example can't work in C/C++, since the check happens after the operation.) I think the poster already knew that, hence the `magic`.
- PeCaN 11y agoGCC[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. 1. https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins... 2. http://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins http://clang.llvm.org/docs/LanguageExtensions.html#checked-a... 3. https://msdn.microsoft.com/en-us/library/dd570023.aspx https://msdn.microsoft.com/en-us/library/dd570023.aspx
- chrisseaton 11y agoThat'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.
- anon4 11y agoIt'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.