Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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



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

Search: