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?