I have a value, of type signed int
, which is always clamped between, for example, ±1073741824 (2^30). I should be able to safely add or subtract any arbitrary value, and if the sum/difference is outside the range it is clamped (any value above the maximum maps to the maximum, and any value below the minimum maps to the minimum). I have the following:
signed int Min(signed int X, signed int Y) {
return X < Y ? X : Y;
}
signed int Max(signed int X, signed int Y) {
return X > Y ? X : Y;
}
signed int X;
void UpdateX(signed int Delta) {
X = Min(Max(X+Delta, -(1<<30)), (1<<30));
}
However, if Delta and/or X is sufficiently large or small that the value overflows or underflows, this invokes Undefined Behavior because there is a signed int
overflow before the clamping. One solution is to use a larger integer type temporarily, but this is not an option for other cases where the largest available type is already being used. How can I safely add then clamp a signed int
without risking invoking undefined behavior?