Given an unsigned integer x and a signed integer dx, what's the most efficient way to perform x = x + dx while preventing over/underflow? I could do something like:
unsigned int x;
int dx;
...
long int result = (long int)(x + dx);
if (result < 0) {
x = 0;
} else if (result > UINT_MAX) {
x = UINT_MAX;
} else {
x = result;
}
But I'm wondering if there's a better way.
EDIT: updated the example to be semantically correct.
The only efficient way is to use inline assembly (add and check the processor flags which are not accessible in C) or to use compiler builtins.
Example:
and the resulting machine code: