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

93

u/crouchingarmadillo May 03 '26

I feel like a lot of these problems with undefined behavior and the like could be fixed by just removing integer promotion and implicit coercions.

Like yeah you introduce an ergonomic problem. But we’re working with a low level language so, we have ergonomic concerns already. Better to be safe and explicit.

37

u/WittyStick May 03 '26 edited May 03 '26

The problem is implicit conversion at the same bit width.

There should never be an implicit conversion from signed->unsigned, unless preceded with a check >= 0.

There should only be an implicit conversion unsigned->signed where the unsigned representation is strictly smaller than the signed one.

unsigned _BitInt(N) <: signed _BitInt(N+1)

That's assuming two's complement, which is a reasonable assumption.

I use this in my numerical tower, not with arbitrary bit width types, but the common power of 2 types we typically use.

uint8 <: uint16 <: uint32 <: uint64
int8 <: int16 <: int32 <: int64 <: int128
uint8 <: int16
uint16 <: int32
uint32 <: int64
uint64 <: int128

Where <: is the subtyping relation. Upcasts are implicit, but all downcasts are explicit.

Sizes should be unsigned. Signed sizes are a workaround for other problems in a type system.

6

u/QuaternionsRoll May 04 '26

I’ve always wondered what it would be like if casting were performed on outputs rather than inputs. Define arithmetic operations such that they can never overflow (e.g. i32 + u32 -> i34) and then require the user to deal with casting the result (i34) to the type they actually need (i32, u32, etc.). Compilers are generally smart enough to eliminate the extra operations when the result is subject to a wrapping cast anyway.

2

u/ExplodingStrawHat May 04 '26

How would exponentials work? Would xy for two u8s produce a u263?

2

u/QuaternionsRoll May 04 '26

No, it would produce a u2039 (ceil(log2(255**255))). It doesn’t really matter though, the upper 2031 bits will never be computed if the result is cast to u8.

→ More replies (1)

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.

→ More replies (1)
→ More replies (4)

4

u/matthieum May 04 '26

Sizes should be unsigned. Signed sizes are a workaround for other problems in a type system.

That's a bold assertion.

In particular, you'd first to justify why unsigned?

Unsigned integers have one, big, glaring issue: the most common value for an integer to have (0) is right at the edge of the representable range. It's very easy to overflow an unsigned integer (u-1 overflows if u == 0).

Signed integers tend to behave a LOT better. Sure there's some risks of overflowing close to MIN/MAX, but those are not nearly as common as 0, 1 and 2.

And even better, when signed integers overflow, you typically get dumb results. Like a negative number when you expected a positive one. Much easier to notice.

2

u/renozyx May 05 '26

It's very easy to overflow an unsigned integer (u-1 overflows if u == 0).

Sure, and? If unsigned integer overflow were trapping by default like they are in Zig, you'd find and correct the issue quickly.

The main problem wih unsigned and C is the "wrap by default" behaviour, most of the time it isn't what you want..

→ More replies (6)
→ More replies (15)

6

u/MadocComadrin May 03 '26

Other issues could also be resolved by other design decisions too. E.g. making a % n Euclidean or Knuthian (which are the only good options imo unless you're writing a CAS, in which case you should support both plus symmetric) removes the signed index with unsigned size issue.

4

u/ExplodingStrawHat May 03 '26

What's the Knuthian modulo? I do agree that the Euclidean one is what you want in 99% of real life scenarios.

11

u/MadocComadrin May 03 '26

It's the same as Euclidean when the divisor is positive but when the divisor is negative, the remainder is negative too. In both (and symmetric) the remainder doesn't depend on the sign of the dividend, which makes them more useful than the other schemes imo.

The wikipedia page for modulo has some nice visualizations https://en.wikipedia.org/wiki/Modulo#Variants_of_the_definition

2

u/flatfinger May 06 '26

In a lot of situations, I think it would be helpful to think of division and remainder not so much as an operation on a pair of numbers, but rather as a family of operations: div2, div3, div4, etc. along with mod2, mod3, mod4, etc. While programs do sometimes need to perform divisions and remainder operations on things other than positive integer constants, scenarios where the divisor is a positive integer constant are the most common, and the Euclidian and Knuthian forms are equivalent.

4

u/Nuoji C3 - http://c3-lang.org May 04 '26

That is just part of the problem. One of the biggest challenges is that an invalid unsigned value looks just like a valid unsigned value eg `0u - 1u`.

While one can make unsigned underflow an error, this then makes (a + b) - c different from a + (b - c). This is just properties of unsigned and has nothing to do with conversions.

3

u/Guvante May 03 '26

Constants tend to be the major problem for dropping implicit conversions.

What is the type of 0?

Sure you can force it to be a single type but that introduces its own problems.

The simplest solve is roughly "integers are the smallest type that fits" and "up casting that is perfectly safe is allowed" aka uint8 -> uint16 or even int16 is allowed since it is always safe.

But now you have implicit conversions...

11

u/mocompute May 04 '26

In my type-inferred language, integer literals like 0 are weak types until they are found in a concrete context and assigned a type. If all contexts are unconstrained, it just defaults to a signed integer. And there are no unsafe implicit conversions in the language, only the safe ones like you suggested.

I don't think there's a problem in allowing safe implicit conversions, but disallowing unsafe implicit conversions.

5

u/gmes78 May 04 '26

That's what Rust does, too.

You can even see it in error messages sometimes, the type shows up as {integer} if it hasn't been inferred yet.

2

u/flatfinger May 07 '26

Treating integers as weak types is generally good, but leaves open ambiguity as to how something like int32a = int32b*100/33; should be processed on a platform where computations with a 32-bit product/dividend would be much faster than with a 64-bit one. My personal preference would probably be to allow programmers to request that such constructs either implicitly use 64 bits or trigger a diagnostic, and have a convenient means of writing the expression that allow compilers to either use an overflow-trapped 32-bit multiply, or use a 64-bit multiply and divide and range-check the quotient, silently yielding correct results in cases where the multiply would overflow.

3

u/jonathancast globalscript May 04 '26

C and C++ already have typed integer constants: 0U, 0L, etc.

Probably needs explicit size_t and ssize_t versions (and explicit size versions? E.g., an explicit 64- or 128-bit version) but it shows the issue is not unsolvable.

(I know about this because Java allows implicit conversion of int to long but does not allow implicit conversion of int to Long. I guess they reconsidered (even widening) implicit conversions at some point.)

3

u/Lurkernomoreisay May 04 '26

c++ 23 added 0z and 0uz for ssize_t and size_t

2

u/mocompute May 04 '26

So, I also added types integer constants with suffixes, but it turned out practically that it wasn't needed, because inference took care of things. However, when I want a size_t explicitly, I usually prefer to add a type annotation to the declaration, because it's more visible.

x: CSize := 0 is equivalent to x := 0zu so I guess it's a matter of taste.

→ More replies (1)

1

u/stone_henge May 04 '26 edited May 04 '26

In Zig, an integer literal is an arbitrarily sized and signed comptime_int until, during compilation, you say otherwise, at which point literals with incompatible signedness or value become a compile-time error.

1

u/CompleteBoron May 04 '26

You a word

2

u/stone_henge May 04 '26

My predecessor was assassinated mid-sentence. I am the /u/stone_henge now.

1

u/Guvante May 04 '26

More trade offs though as now Foo(0) is different than the same function inlined.

Trade offs are fine just noting that sometimes making the thing that is obvious work that way is a bit of work.

→ More replies (2)

2

u/RedCrafter_LP May 03 '26

My language features checked and unchecked operator versions for everything like + and +? or *= and *?= if you want to create a codebase without implicit issues you can disable the panicking ones and just allow those returning a handled result.