To handle unsigned integer wraparound issues, I am planning to use the following checks.
Addition: Performing a postcondition check to ensure that the result of the unsigned addition operation is not less than the first value
void fn(unsigned int a, unsigned int b)
{
unsigned int sum = a + b;
if (sum < a) {
// Wraparound occured. return error.
}
/* ... */
}
Subtraction: Performing a postcondition test that the result of the unsigned subtraction operation is not greater than the first value:
void fn(unsigned int a, unsigned int b)
{
unsigned int difference = a - b;
if (difference > a) {
// Wraparound occured. return error.
}
/* ... */
}
I assume these checks will works irrespective of compilers. Is there any better way to handle unsigned integer wraparound issues? I am looking for cross platform support.