2

I'm curious, is it possible to write an all-encompassing implementation like

template <typename T> 
bool overflows(T a, T b)
{
  // ... Returns true or false depending on whether a+b overflows
}

????

If not, can someone at least show me how to write an implementation of

   bool overflows (unsigned int a, unsigned int b)
   {
       // ... returns true or false depending on whether a+b > ~0
   }

???

Since I don't have a Computer Science degree, I don't have any formal education about how programs are supposed to handle overflow, although I understand the concept of overflow (If our range of numbers is, say, 0,1,...,127, then the + operation doesn't "work" on 64+64, 65+63, 66,62, etc.)

  • The only value for which `a+b` is not `>~0` is `~0` itself. ;) Unsigned arithmetic is defined mod 2^n for some n guaranteed in C++. Signed arithmetic is ... far less guaranteed. – Yakk - Adam Nevraumont Mar 25 '15 at 22:34
  • 1
    In floating-point, “`a+ b` overflows” is **defined** as “`a + b == +inf`”. I don't know what else you want. But your `~0` makes me think that you are not interested in floating-point, and then you should pick some tag you are interested in. – Pascal Cuoq Mar 25 '15 at 22:35
  • I don't know the answer to this, but I would explore `decltype`. It returns the type of an object. From the type of an object, you can infer the max value it may properly store. From the max value, you can infer if there will be overflow for a given operation. – The Vivandiere Mar 25 '15 at 22:35
  • http://stackoverflow.com/questions/199333/how-to-detect-integer-overflow-in-c-c – Drew Dormann Mar 25 '15 at 22:43

1 Answers1

1

Since you are asking about addition alone, you can do it for the types with numeric_limits<T>::max() defined along with an additional assumption that at least one of a and b is non-negative. (There is likely a way to work-around it but I don't see a succinct one.)

template <typename T> 
bool overflows(T a, T b)
{
  if(a < b) return overflows(b,a);
  //Since we assumed at least one is non-negative, this now makes sense.
  return b < std::numeric_limits<T>::max() - a;
}
Pradhan
  • 16,391
  • 3
  • 44
  • 59