Hacker News new | past | comments | ask | show | jobs | submit login

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.

1. https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...

2. http://clang.llvm.org/docs/LanguageExtensions.html#checked-a...

3. https://msdn.microsoft.com/en-us/library/dd570023.aspx


You may be interested in 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... .

(Note that your second example can't work in C/C++, since the check happens after the operation.)


> (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`.


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: