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

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.