Preventing Integer Overflow in Physical Computations
Integers overflow. That is not a controversial statement. What is surprising is how easily overflow can hide behind the abstraction of a units library.
Most developers immediately think of explicit or implicit scaling operations —
calling .in(unit) to convert a quantity, constructing a quantity from a different
unit, or assigning between quantities with different units. These are indeed
places where overflow can occur, and the library cannot prevent it at compile time
when the values are only known at runtime. But at least these operations are
visible in your code: you wrote the conversion, you asked for the scaling,
and you can reason about whether the multiplication or division might overflow
your integer type.
The far more insidious problem is what happens when you don't ask for a conversion.
When you write 1 * m + 1 * ft, the library must automatically convert both
operands to a common unit before performing the addition. That conversion —
which you never explicitly requested — involves multiplication or division by
scaling factors. With integer representations, those scaling operations can
overflow silently, producing garbage results that propagate through your
calculations undetected.
No compile-time programming can prevent this. The values are only known at runtime. But very few libraries provide proper tools to detect it.
This article explains why that limitation is real, how other libraries have tried to work around it, and what mp-units provides to close the gap as tightly as the language allows.