r/cpp • u/mateusz_pusz • Apr 20 '26
Preventing Integer Overflow in Physical Computations - mp-units
https://mpusz.github.io/mp-units/HEAD/blog/2026/04/11/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.
View all comments
Show parent comment
2
u/mateusz_pusz Apr 20 '26
Well, I think it depends on the reader. Some may be upset with the AI-like formatting. Others will appreciate the content and the time I put in to answering all the questions with details. As I said, all the technical content is written by me before AI polishes the final answer.
You may not know, but I am enjoying my vacation in Italy now and I spent 3 hours already answering the questions here today. It is not easy to find the time to design, implement, and document the library, write posts about it and answer questions or comments from the users all by myself. All of this having family responsibilities and daily work.
Said that, I am sorry if you find those AI-styled answers inadequate or offending. But I try to do my best with the knowledge, time, and tools I have at my disposal...