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
10
u/STL MSVC STL Dev Apr 20 '26 edited Apr 20 '26
This appears to be AI-generated. Please read the subreddit sidebar for our rules, and do not use AI to generate (or "polish") your comments on this subreddit.
I know you're working on an important library that's under consideration for Standardization, so it's great that you're commenting here. However, AI-generated comments are completely counterproductive for what you're trying to accomplish.
Edit: I see that others have already discussed this with you below. I'll add that it might seem tempting to have AI assist you if you aren't a native English speaker, but the problem is that it makes it incredibly hard for readers to figure out what you're actually trying to communicate, since others are using AI to generate slop with no actual value. So you aren't "polishing" your words, you're just covering them under a big pile of slop that nobody (who can tell the difference) wants to read. People would much rather read somewhat disjoined/less-than-fluent English and have a direct view of your technical insights that way.