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

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..

1

u/matthieum May 05 '26

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

  1. They're trapping by default in Rust too, in Debug. But not in Release, because arithmetic-heavy code suffers heavily, auto-vectorization gets disabled, etc...
  2. It's always fun when the problem only appears in production, at 3am, and you get paged... isn't it?

The main problem with unsigned [...]

is the hard cut-off at 0 which screws up arithmetic rules.

In fact, wrap-around behavior, despite being strange initially, plays nice. With wrap-around, i + (j - i) == j, no matter what values i and j have, because in case of overflow (i > j), the two overflows cancel each other out like magic.

So from a mathematical intuition point of view, wrap-around means you can take an algorithm that's correct in infinite bit-width maths, and use with finite bit-width, and still get the correct result.

This does NOT work as well with trapping. Trapping means that + is no longer associative (!), for example. Surprise!

Note: I am not exactly advocating for wrap-around, it has its own issues.

2

u/initial-algebra May 07 '26

This does NOT work as well with trapping. Trapping means that + is no longer associative (!), for example. Surprise!

It's a tradeoff. With wrapping, you get nice algebraic properties. With trapping, you get nice ordering properties. Sometimes you want one, sometimes you want the other, so it should be explicit. Though, in the case of dealing with sizes, offsets, pointers, data structures etc. you almost always want trapping, except for special cases like ring buffers, so I think it's a sane default for a systems language.

1

u/matthieum May 08 '26

I think it's a sane default for a systems language

Performance-minded folks would disagree. Trapping implementations are software emulations and are not auto-vectorizable :/

Instructions sets (x86/64) only natively support wrapping. Anything else has to be "emulated", and emulations are typically not vectorizable.

This leads to a chicken and egg problem:

  • Languages use wrapping semantics, because that's native speed.
  • Chips makers only offer wrapping semantics, because that's what languages use.

I was really looking forward to the Mill CPU, where the designers actually offered full-fledged integer operation behaviors -- wrapping, trapping, saturating, widening -- for both scalar & vector operations. WOOT. Been waiting for over a decade though, wonder how the guys are doing :'(


Even assuming native instructions, though, the fact that associativity is lost makes me look twice, to be honest. I wonder how much performance is lost to non-associative arithmetic.

In high-level languages it's likely the correct semantics, but systems languages nowadays are the languages you reach for when performance matters... so dinging their performance is a bit of a non-starter :/

2

u/initial-algebra May 08 '26

See, to me, systems programming is distinct from number crunching. There is obviously some overlap, as when you're implementing fundamental data structures and algorithms, you want them to be efficient, but correctness is even more important, and having to be a bit more verbose to go the other way is fine by me.

Of course, the ideal solution would be to be able to narrow the range of integer types down even further using refinement types. Then, you may not have to give up any properties, because you can know when the result of an operation can never overflow (barring pathological cases where memory would already be exhausted, for example), and it can be compiled to the most efficient implementation available.

1

u/matthieum May 09 '26

See, to me, systems programming is distinct from number crunching.

You are technically correct! In fact, did you know that when Graydon Hoare created Rust it had, among other things, built-in big integers? It was intended to be a systems programming language where correctness comes first.

In practice, however, systems programming language are the only languages available who can be used for high-performance (or low-overhead) tasks, and therefore seem to invariably be coopted for it.

Of course, the ideal solution would be to be able to narrow the range of integer types down even further using refinement types. [...]

Did you know Rust is getting generic integers? The idea is to have i<N> and u<N> where N is the bitwidth, and define the current crop of integers as synonyms, so type i32 = i<32>; for example.

Technically, this could be used to implement widening. Ie, the output of i<5> + i<5> is i<6>. Crude, but simple.

Anyway, whether full integer range or just bitwidth, I'm not sure how practical it could be. Multiplication really widens very quickly. i<32> * i<32> is i<64> already.

I guess you'd need checked narrowing regularly to keep things under control?

Hum... who knows, maybe it'd work.

2

u/initial-algebra May 09 '26

What I have in mind are integers that are bounded by actual memory usage, for example sizes/lengths, (valid) offsets/indices, reference counts etc. Now, I have no idea how that would actually be expressed, or the exact rules around using them in a way that would guarantee no overflow. Only being able to mention such a quantity at most once in an expression would be a start, but how to track/enforce this...

1

u/WittyStick May 04 '26

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

That's actually the easiest argument to make - a "negative size" makes zero sense. The size of something is a natural number.

It's the signed size advocates who need to make the justification, and I find their arguments pretty uncompelling - particularly when we fix the implicit conversion issues as described.

The underflow at zero might be an issue for novices - but using signed integers replaces that with overflow at INT_MAX or underflow at INT_MIN. You don't simply remove the problem by making signed sizes - you actually make it more likely that a bug will remain for longer because these cases are less likely to appear in production. Ie, code might work fine for some time, until you scale beyond 2GiB and the bugs start appearing.

Also we have the issue that signed integer under/overflow is UB, where unsigned wrap is well-defined. On x86_64, addition, subtraction and multiplication of signed integers will overflow, but division will trap.

3

u/brucifer Tomo, nomsu.org May 04 '26

That's actually the easiest argument to make - a "negative size" makes zero sense. The size of something is a natural number.

I think it's fine to say that sizes are nonnegative by nature, but any arithmetic operation that involves subtraction or mixes signed and unsigned integers needs to be represented as a signed integer unless you want underflow behavior. For example, if you do delta = size1 - size2 or offset = size * signed_stride or diff = abs(size1 - size2) or i -= 1, then you need to cast everything to signed values, because the calculation could very easily underflow. And casting has its own set of correctness issues, like how half of all unsigned integer values are not representable as signed integers of the same bit size.

If much of the code that uses sizes does underflow-prone arithmetic, then I think it makes sense to have sizes use signed integers to prevent the bugs that are likely to occur, even if the tradeoff is that the data representation of sizes admits the possibility of a negative size.

1

u/WittyStick May 05 '26 edited May 05 '26

I think it's fine to say that sizes are nonnegative by nature, but any arithmetic operation that involves subtraction or mixes signed and unsigned integers needs to be represented as a signed integer unless you want underflow behavior.

I agree, and this is why unsigned are a subtype of signed with implicit conversion - but not at the same bit width. This solves the issue of mixing signed and unsigned arithmetic - the result is the least upper bound of the arguments.

Eg, if we have x : uint32, y : int32, then x + y results in int64 - the LUB of uint32 and int32. The result can't be int32 because int32 is not a supertype of uint32 - so if we wanted an int32 result we need an explicit coercion (or a different arithmetic mode, controlled via a dynamic variable).

For example, if you do delta = size1 - size2 or offset = size * signed_stride or diff = abs(size1 - size2)

The names delta, offset and diff are dead giveaways that we're not actually talking about a size, but a difference between two sizes. This should have a type distinct from the size type, and yes, this should be a signed type. In C we have a type ptrdiff_t for this purpose - which is of course signed - but it still has all the problems of C's implicit coercions.

Using my approach where implicit conversion only happens where no information is lost, these problems largely go away.

3

u/brucifer Tomo, nomsu.org May 05 '26

Eg, if we have x : uint32, y : int32, then x + y results in int64 - the LUB of uint32 and int32. The result can't be int32 because int32 is not a supertype of uint32 - so if we wanted an int32 result we need an explicit coercion (or a different arithmetic mode, controlled via a dynamic variable).

Implicit conversion to a larger type is not really a viable option in most cases. In most languages, 64-bit sizes are common, which would require promoting to a 128-bit integer. Ignoring platform support issues, you still have the problem that this promotion is contagious, so all your arithmetic ends up being promoted upwards to 128 bits, which hurts performance and requires you to downcast if you want to store the value in a 64-bit field or variable.

The names delta, offset and diff are dead giveaways that we're not actually talking about a size, but a difference between two sizes. This should have a type distinct from the size type, and yes, this should be a signed type.

Above, you suggested a strategy that preserves information at all costs. However, if you subtract one N-bit unsigned value from another, the result would need N+1 bits to fully preserve information because the range is [-UINT_MAX, +UINT_MAX]. So, you'd still have the same promotion contagion issues for subtraction. For example, if you wanted to get the last character in a string, last = s[strlen(s)-1], then the subtraction between strlen(s) and 1 would force the result to a 128-bit signed integer, which is incompatible with pointer arithmetic on most machines, so you'd have to downcast to a 64-bit value. This seems both inefficient (doing the arithmetic with 128-bit integers) and onerous, with no upside, since it does nothing to address the potential bug when strlen(s) == 0.

In C we have a type ptrdiff_t for this purpose - which is of course signed - but it still has all the problems of C's implicit coercions.

In C, sizeof(ptrdiff_t) == sizeof(void*), which does not follow the scheme you suggest, since it cannot represent all differences between pointers. Similarly, ssize_t cannot represent the difference between two size_t values.

3

u/matthieum May 05 '26

That's actually the easiest argument to make - a "negative size" makes zero sense. The size of something is a natural number.

This is not the question asked, unfortunately.

The question asked is to justify why unsigned should exist in the first place, and specifically, whether unsigned really pull their weight.

Signed integers are necessary for general arithmetic, anyway. Is adding unsigned integers on top really worth it?

I'm not convinced.

I mostly see people adding them because "that's how it's always been", but I rarely see a compelling costs/benefits analysis.

Also we have the issue that signed integer under/overflow is UB, where unsigned wrap is well-defined. On x86_64, addition, subtraction and multiplication of signed integers will overflow, but division will trap

We don't. That's a problem that is specific to C and C++, it's not a universal property of signed vs unsigned.

GCC and Clang both offer -fwrapv, which the Linux kernel uses, to have wrap-around for signed arithmetic too.

Rust offers either panic on wrap or wrap-around (your choice).

Java only wraps around.

The underflow at zero might be an issue for novices

In my experience they're an issue for everyone...

but using signed integers replaces that with overflow at INT_MAX or underflow at INT_MIN.

Yes, I explicitly mentioned it.

You don't simply remove the problem by making signed sizes - you actually make it more likely that a bug will remain for longer because these cases are less likely to appear in production. Ie, code might work fine for some time, until you scale beyond 2GiB and the bugs start appearing.

Overflow is still a risk, however:

  1. Using signed integers drastically reduces the risk of occurrences, because large number (billions) are much less frequent than small numbers (0, 1, 2).
  2. Using unsigned integers barely raises the cap at which overflow will occur -- a measly 2x. If you're playing with numbers high enough to overflow your signed integer, you're much better off doubling the bit-width than switching to unsigned -- much higher tolerance margin there.

1

u/flatfinger May 05 '26

Full-sized unsigned types are useful for modular arithmetic, and unsigned types are useful smaller than int are useful for assembling numbers out of smaller components. Further, especially in the 16-bit era, there were a lot of things whose natural upper bound fell between 32768 and 65535.

1

u/EggplantExtra4946 May 06 '26 edited May 06 '26

Signed integers are necessary for general arithmetic, anyway.

Not if all you do is add and multiply unsigned integers. Even if you do subtract unsigned integers and it overflows, the actual bit pattern will be the same as if it were a signed integers and if you use that underflowed unsigned integer to an other unsigned integer, it will produce the correct result, the same result as if you were subtracting and adding signed integers.

Essentially, unsigned integers can be transiently used as signed integers when evaluating an expression whose result will be >= 0 but that can have < 0 temporaries.

Overflow is still a risk, however:

And you can more easily check for overflows in unsigned integers without intrinsics than with signed integers. For checking that an addition did not overflowed, you only need to check that the result is superior to both operands of the addition. If you also know that only one of the operand can get big, you only need to check one operand instead of two.

Another benefit of unsigned integers: when compiling a switch statement to a jump table, in the case of a signed integers you need to check that it is < to the length of the jump table and >= 0. Whereas with unsigned integer you only need to check that it is < to the length of the jump table. Of course you can cheat and treat the signed integer as unsigned integer and perform only an upper bound check, but in that case you're implicitly casting the signed integer to unsigned.

Overflow is still a risk, however:

  1. Using signed integers drastically reduces the risk of occurrences
  2. Using unsigned integers barely raises the cap at which overflow will occur

What kind of fallacious argument is this? If overflow is a problem then it's a bigger problem for signed integers, at the very least signed integers certainly don't reduces the risk, they obviously increase it.

Unsigned integers are also better for bitwise operations, logical right shift is better than arithmetic right shift and it's a common operation.

Outside of comparisons of signed integers, I'm not convinced you actually signed integers for arithmetic, unsigned integers are enough. Or dare I say, unsigned integers are the superior signed integers. For the processor it's all the same anyway.

2

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

Interestingly enough, given that you need to check that a signed value is in the interval 0 <= x <= MAX, you only need to check (unsigned)x <= MAX, and usually compilers already optimize for this fact, so you can write it as x >= 0 && x <= MAX without it being two checks.

1

u/EggplantExtra4946 May 09 '26 edited May 09 '26

Interestingly enough, given that you need to check that a signed value is in the interval 0 <= x <= MAX, you only need to check (unsigned)x <= MAX

Not quite. This optimization is only valid if we know that MAX <= INTMAX_MAX. The compiler can know that if MAX is a constant but then this optimization would only apply to fixed-size buffer with a capacity known at compile time. The compiler can not know that in general without interval analysis and possibly more if MAX is variable or expression reading from the heap. A simple optimizer doing only straightfoward dataflow optimizations cannot do this optimization.

If MAX > INTMAX_MAX and INTMAX_MAX < x <= MAX, then (unsigned)x <= MAX is true but we also have (signed)x < 0.

2

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

I wrote MAX here in capital letters to indicate that it's a constant. If the compiler doesn't do it for you, say you provide it as a constant, then you need to do it manually to get rid of the comparison yes.

1

u/EggplantExtra4946 May 09 '26 edited May 09 '26

As you can see, neither GCC nor LLVM Clang can perform that optimization with -O3 when MAX is not known at compile time.

https://godbolt.org/z/hcs4a1o16

https://godbolt.org/z/WMr7cMqc3

If I use 4096 instead of array->length, your optimization is peformed but so what? Almost nothing except I/O buffers is going to use a fixed-size array of capacity known at compile time, and even those might use a capacity that can be modfied at runtime, so effectively this optimization will be performed rarely and almost all properly done bounds checks involving signed indexes will require 2 conditionals.

1

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

Well, that certainly depends. The C3 stdlib uses a lot of interval checks with a known max value when checking size parameters. This is for robustness, since often you have code that is written for some int type, allowing it to have values up to UINT_MAX / INT_MAX. But taking into account calculations, it's not safe to use such large numbers.

The lack of max value checks is incidentally a big cause of vulnerabilities.

1

u/marshaharsha May 05 '26

What do you say to the argument that it’s good to use the operation with UB, since that keeps open the possibility that tooling will warn about the problem?

1

u/flatfinger May 05 '26

Undefined Behavior is lousy from that perspective, since while it would allow compilers to issue diagnostics, Dennis Ritchie observed that compiler writers preferred to use the Standard's failure to accurately specify things as an excuse to process them nonsensically, and the situation has since Ritchie's time gotten even worse.