Search code examples
c++mathsubtractioninteger-arithmetic

Subtract unsigned ints into signed long result. Never negative?


Found a bug in my code and noticed the following, when subtracting 2 numbers like

unsigned int a, b (with b > a)

signed long result = a - b

The result is always positive, even though b is larger. I expected that since result is signed, the result would be converted to signed too, but apparently not. How can i fix this?


Solution

  • The problem is, your math is happening -- with unsigned ints, resulting in an unsigned int -- before the value is converted to a long. When an unsigned type is converted to a larger signed type, the value doesn't change. So your result will only ever have a chance of being negative if long and int are the same size.

    Try converting at least one of your values to a long before you do your math. That should be enough to get your result to be signed.