r/ProgrammingLanguages • u/Nuoji 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
r/ProgrammingLanguages • u/Nuoji C3 - http://c3-lang.org • May 03 '26
View all comments
Show parent comment
1
u/EggplantExtra4946 May 05 '26 edited May 05 '26
You can iterate backwards like this:
or eventually like this:
for (size_t i = length-1; i > 0; i--) { array[i] } array[0]Mixing signed and unsigned integers like that is a receipe for failure. C allows that but a decent type system shouldn't. The real issue is C's type system poor handling of integers, it's not the fault of unsigned integers.
Again, type system issue and count (and sizes) should be unsigned in the first place. (Also any interger literal imo, unless the interal is negated in which case it should be a signed.)
If you're doing a substraction you can compare the operands before doing the substraction. But frankly I used unsigned integers everywhere, always have overflow/underflow in the back my mind and "checking for underflow" is just something that doesn't come up. If anything, when it does come up, when a substraction can result in a negative number I'll let it wrap around, knowing that if I need to add that substraction result to an unsigned integer, the addition will overflow and effectively perform a substraction and give the correct result, thanks to the arithmetic properties of unsigned integer wrapping. That's precisely what makes unsigned integers easy to work with, even in the eventual case of an underflow. Effectively underflows just doesn't really matter in result of temporary expressions, concerning the correctness of the overall expression. Overflows are the real issues but if you pick width large enough it shouldn't happen. For completeness, a double underflow would be another issue but if you're using unsigned integers because the quantity (such as memory length/size) can't be negative, you're going to only have the one subtraction, no 5 in a row. Or if you do you can refactor
a - b - c - d - eintoa - (b + c + d + e).The type system should disallow it, unless unsigned numbers is narrower than the signed integer, or if you know that the signed integer is positive, etc.. Like others have said ITT.
What I do in my language is make all integer literals unsigned with the narrower width that can contain them, but if the integer literal is negated, I constant fold it and set the type of the resulting number to signed, with the same width.
Nah it's clear enough, you're downvoted because of the meaning of your arguments, not because of your form.
Another reason for unsigned is that optimizing compilers of C/C++ won't break your code beacuse they feel they can do whatever they want in the case of undefined behavior and basically all signed arithmetic operations are (or were, maybe not true in new standards) UB upon overflow/underflow.