difference between 2 unsigned integers

Hello,
How can I find the difference between two unsigned integers, without converting anything to signed integers or creating a if statement?

Basically, what I am trying to do is this:

abs(int1-int2)

but of course this won't work if int2 happens to be bigger than int1. Of course I could just do this: abs(int(int1)-int(int2)) but I was wondering if there was a more elegant "difference between" function I could implement, mainly because I don't know the data type of the integers I am working with and it is conceivable that a simple "int" might not be big enough.
Last edited on
abs(int1-int2) works fine

in the case that int1 and int2 is of type MyInteger, MyInteger needs to be smart enough to handle operator-() so that the result makes sense (no over or underflows)
That's exactly the problem; they're unsigned...

I was hoping for a function that could find the difference between 2 numbers without subtracting them arbitrarily and removing the sign, like abs() does.
Last edited on
but unsigned works fine with that snippet - I just verified with a compile and run

why not keep it simple? if you prefer, you can complicate things and do this:

1
2
3
4
template< typename T >
T absdiff( const T& lhs, const T& rhs ) {
  return lhs>rhs ? lhs-rhs : rhs-lhs;
}

but it's a bit of overkill for unsigned

edit: changed name from abs() to absdiff()
Last edited on
Topic archived. No new replies allowed.