0

How can it be possible to determine if subtracting n from an unsigned int will roll over to a negative value, considering that casting to a signed int can result in a negative value already?

Example

#include <iostream>
using namespace std;
int main(){
    unsigned int i = 2147483647*2;
    if((int)i - 1 < 0){
        cout << "rolled over";
    }
    else {
        i = 0;
    }
    return 0;
}

In order to check if subtracting from an unsigned int would roll over, you could cast it to an int first. However, if the unsigned int is > the max int value, you will already end up negative. So how can I prevent an unsigned int from rolling over?

  • 2
    subtracting `n` from an `unsigned int` will never roll over to a negative value, considering unsigned types do not represent negative values. – eerorika Mar 04 '19 at 18:29
  • Your research would probably have given you better results using the keywords _overflow_, _underflow_ than _"rollover"_. – πάντα ῥεῖ Mar 04 '19 at 18:30
  • If the number you are subtracting is larger than the number you are subtracting from, you get a negative value. For unsigned integers in c++, this is performed with modulo arithmetic, so would "wrap around". Just compare the two operators. – François Andrieux Mar 04 '19 at 18:31
  • In this particular example: `if (i < 1)`. – Toby Speight Mar 04 '19 at 18:39
  • Assuming `i` is the value of the unsigned int, and `n` is the amount being subtracted, then `if (i < n) cout << "value underflow";` . Depending on your use case, it may be appropriate to throw an error, to allow the underflow to wrap around, to log a message, and/or to pin the value to some minimum (e.g., `0`). – Eljay Mar 04 '19 at 19:22

0 Answers0