r/ProgrammingLanguages • C3 - http://c3-lang.org • May 03 '26

Blog post Unsigned Sizes: A Five Year Mistake

https://c3-lang.org/blog/unsigned-sizes-a-five-year-mistake/
91 Upvotes

115 comments sorted by

View all comments

Show parent comment

1

u/WittyStick May 04 '26 edited May 04 '26

My language is dynamically typed where this is a bit simpler - the result is whatever type is sufficient to fit the resulting value without loss of precision - though I don't have any separate dedicated types beyond int128 other than arbitrary precision integers. The arithmetic mode can be overridden with a dynamic binding - which can be one of modular, strict (aka checked, trap on overflow), precise (no information loss) or saturating.

In terms of encoding it in a static type system, it can get quite complex, requiring refinement or dependant types, and some operations like pow aren't trivial and could nuke your compile times. Basic addition and multiplication are fairly simple - for addition/subtraction you need at most 1 bit more that the widest input type, and for multiplication you need up to twice as many bits as the widest argument type. Div only needs the size of the first input as the smallest integer divisor is 1.

add, sub : _BitInt(N), _BitInt(M) -> _BitInt(MAX(N, M) + 1)
mul : _BitInt(N), _BitInt(M) -> _BitInt(MAX(N, M) * 2)
div : _BitInt(N), _BitInt(M) -> _BitInt(N)
pow : _BitInt(N), _BitInt(M) -> _BitInt((N+1) * 2^M)

There's more complexity if you were mixing signed and unsigned arguments, but I would advise against doing this and use the technique I previously described of permitting unsigned to be implicitly converted to a wider signed type first.

2

u/QuaternionsRoll May 04 '26

Your mul bound could be tightened from MAX(N, M) * 2 to N + M, and your div bound should be loosened from N to N + 1, as INT{N}_MIN / -1 == INT{N}_MAX + 1.