by kstenerud · 4y ago · 0 comments
I'm now back in the signed camp. Signed integers make it a lot easier to sanity check integer subtraction when negative values are disallowed (a common situation), and it's easy to reason about. Also, not converting between signed and unsigned avoids accidental conversion overflows due to different expectations, so keeping it signed bypasses that whole can of worms while maintaining maximum flexibility.
Unsigned gives you 2x the positive numeric range, which 99.999% of the time you'll never use (and if you did, underflow detection would become a nightmare).
I can't think of a single time I've heard someone complain "I wish Java's long type supported up to 16 quintillion instead of a paltry 8 quintillion"
At the end of the day, code is for people, so keep it easy for people.
This adds more 'value' to the code for people than allowing them to switch their brains off because something is 'unlikely' to happen. A large class of bugs exists because people assume stuff is unlikely.
I also think one has to distinguish between API and actual code.
If you write a lib that takes inputs that should never be negative you can express this without writing a single line of documentation about it (or if you do, requiring the user to read it) by using unsigned types in these places.
You can still use signed types in your actual library code if you want/must/believe in that but do not pollute the outside API with them if unnecessary.
Imagine you have a bug in your program. If you intend for a value to be non-negative and use a signed integer, you get a negative value. Your code is broken. You didn't want a negative value. But you do have have a very easy way of checking for this at runtime, at least.
Now imagine you instead use an unsigned integer. The bug is still there but now it manifests as overflow or underflow. Your program is still broken. Nothing about using an unsigned integer saved you. And worse, you don't have an easy predicate to check that something has gone wrong.
I think this can only be a reasonable choice if you are working in a language that has dynamic checks for overflow and so using an unsigned integer enforces not only the predicate that the value is nonnegative but also that all operations stay within its expected arithmetic domain.
thread 'main' panicked at 'attempt to subtract with overflow'
If it was an int at the function signature and you got -1 what would you expect to happen? It's the same thing.
How could you possibly check this using types that cannot represent what you are checking for?
The same thing, but worse, can happen with signed integers. (-3)-INT_MAX is either some huge positive number, or something crazy because it's undefined behavior and the compiler is allowed to do anything it wants.
I can understand where they come from, especially regarding error handling: for integers whose value must not be negative, it is easier to check for underflow by checking if the result is not negative rather than by checking that the result is not eg smaller than the previous value (eg for addition).
That being said, "number must not be negative" really ought to be encoded in the type system, so that the user of the type knows that they must actually look for underflow.
I guess that part of the problem is that we don't want to check for underflow after each operation, so checking the negativity is a way to "coalesce" several checks after multiple operations. However this is fragile, because the multiple operations could end up producing a positive value, even if some intermediate values where negative.
For full safety, I don't see how we could do better than checking after each operation right now. If we're doing this, I feel like checked_add and friends from rust is a better fit than cramming an unsigned int into a signed one.
I wonder if we could design an integer type with 63 bits of value, plus one bit of "overflow/underflow poison", such that any operation that would under/overflow would saturate that bit to one, but otherwise still perform the operation on the value part. That would allow to coalesce multiple checks while keeping safety even in the presence of multiple faulty operations. I wonder how it could be implemented efficiently though
In terms of the C standard, "3-4" for unsigned ints is modular arithmetic, and the "wrong thing" is assuming that it will do anything other than wrap around. This is very clearly defined, and implied whenever you see an arithmetic expression on unsigned integers.
Maybe you want to do some weird bit banging trickery, and that's fine too, but it should require an out-of-the-way function call.
Many languages optimize numeric operations and DX around numeric types for efficiency rather than correctness, and make the latter high-friction. (Wrap-around subtraction, decimal literals being treated as IEEE floats, etc.)
The exceptions (or cases where it is merely less true) tend to be very high level, dynamic languages.
Ada's "Positive" or "Natural" or
subtype X is Integer range Y..Z;
expresses intent (well expresses requirement really), it also enforces that constraint, so it's not merely an assumption.So, let's make an odd_int_less_than_20587 type and a billion of other types? "Not negative" normally helps only one tiny bit towards documenting anything about the accepted values. Making a separate type for that and complicating everything is ridiculous.
> If you write a lib that takes inputs that should never be negative
Have you ever compared the difference between two unsigned integers? Because unsigned integers don't have "natural" subtraction. Did you ever find the need for signed numbers to interact with unsigned numbers? Because if you did, it's a bad idea to separate them without need. Premature isolation is a prime cause of complexity.
Yes, what's wrong with that ? Every variable's type should be defined as precisely as possible when meaningful, that's the whole point (and C/C++ not easily allowing to do that is one of their biggest drawbacks imho.)
Bounded integer types have been extremely useful for me on a few occassions, and I wish more languages had type systems powerful enough to support them. They also address your concerns about subtraction.
Yees?
Bounded integers are a relatively common feature of programming languages (and one which is sorely missing from Rust, it's technically possible currently but not super fun, when fleshed out enough const generics should make them much nicer, possibly even built-in)
Yes, and at least in C++ it isn't that difficult to trivially generate these types as you need them with a modicum of template-fu. You don't need that many integer type templates to capture most of the common cases and provide contextually sane operators. This might be a little more difficult in other languages.
This is pretty standard type safety practice and usually well worth it in terms of writing robust low-defect code.
I see your point, but I think that (while not always), it can still be pretty helpful to add your custom types to make invalid states unrepresentable.
This can sound ridiculous on something like C, but if your language has refined types, it's not that bad.
For example, this doesn't look awful to me:
``` type WeirdId = Int Refined (Odd And Less[20587])
val myId: WeirdId = 5 // OK val myInt: Int = myId // Can be used as an Int val myRuntimeId: Either[String, WeirdId] = refineV[Odd And Less[20587]](myId + 2) // Runtime Check val myInvalidId: WeirdId = 6 // Compilation Error ```
This is one of the best features of the pascal family:
http://www.delphibasics.co.uk/Article.asp?Name=Sets
(look in "SubRanges")
That, plus the type incompatibility that arises from mixing such types with other integer types.
You could also argue that subtraction for unsigned numbers is only partially defined, just like for signed numbers. But that would be missing the point, since most numbers in practical programs are small, and for these numbers the signed range is indeed much more useful since subtraction is defined for signed integers (e.g. i32) for small numbers. This is not the case for unsigned, where 3u-4u is usually not what you want.
They are not. I write mostly Rust these days.
In reality, like all C keywords, it's completely misleading and actually really means "weird_arithmetic_mode_that_will_mess_you_up".
Not sure what they mean about it being misleading though. They might prefer it if they were called "modular integers" instead of "unsigned integers" but that would lead to confusion with modules IMO.
In short, the operations on `unsigned int` do not really behave like "non-negative integer"; as such it's a weird match to use them for that purpose.
- dangers of mixed signed/unsigned code (signed values MUST exist, but unsigned values don't have to)
- more cognitive load to read and understand unsigned underflow detection code + issues once you exceed the halfway point
This is why Java offered signed integer types only (I think they should have allowed unsigned as well, but for different reasons)
This is a poor, poor substitute for contract checking.
My preference is to minimize surprise. If everyone is used to using signed types for everything, you better have a good reason for using something else, and leave that justification in a comment
Yes, and let's start with overflow behavior because it's much more relevant than the type domain.
If overflow isn't encoded by the type, there is just no way to correctly set a strict domain.
You see, doesn't make a lot of sense to distinguish between positive and negative in the end. From a mathematical point of view negative integers have the same dignity of positive integers since a couple of centuries. The same operations that apply on positive integers apply on negative integers, and not only that, an operation between two positive integers can as well result in a negative integer!
The unsigned type was created just to have one more bit if you *are sure* you have only positive integers. That could had a sense in the era of 8/16 computers. Nowadays that we have 32 or 64 bit computers does really that extra bit count that much? I don't think so... 2 billions is plenty enough for most usages.
I totally agree!
After some horrible bugs caused by unsigned integers in innocent looking C/C++ code, I'm 100% in the signed camp. The only time I use unsigned is when I need well-defined overflow behavior (which is rare).
As a bonus, using signed loop counters in C/C++ code enables certain kinds of compiler optimizations (based on the fact that signed integer overflow is undefined behavior): http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
The correct way is using ints, e.g. "int x = b[i] & 0xff;". Pretty much you should do math with int and long only. java.util.Integer/Long nowadays have static methods to work with unsigned types if you need them.
Once you remember that you need (the annoying) "0xff", you'll be free from errors. It has been there for 24 or so years. Other than that wrap your arrays into ByteBuffer and use provided utility.
The memory layout of the classes is quite immaterial here as the operation do happen within CPU registers.
[0]: https://docs.oracle.com/javase/specs/jvms/se12/html/index.ht... [1]: https://en.wikipedia.org/wiki/List_of_Java_bytecode_instruct...
That Java has no support for unsigned integers is a very common complaint.
Several APIs in the VFX arena (Pixar OpenSubD, Pixar USD, and Foundry's Katana GeoLib API) all use signed ints for indices which I've occasionally argued against, with the response being "Google's coding standard says don't use them".
As for 64-bit values, unless you can foresee requiring > 8 quintillion, unsigned isn't buying you anything.
There are a number of ways to handle this:
- Use unsigned 32-bit (gives you a little bit more runway, but you'll still hit the end hard)
- Use 64-bit values (ends your problem once and for all, but costs double the memory so now you have a new problem)
- Use 40-bit values (Gives you a lot more runway, but costs CPU)
I looked at OpenSubdiv extensively. There are no good reasons to use signed in the cases I opened the ticket for and making sure the code inside the lib does the right thing with unsigned arithmetic is trivial.
But someone still needs to do that and writing that "Google (essentially) says you don't need to" in their style guide is much less work. ;-)
Timestamp arithmetic is a common case where unsigned integers with silent overflow is superior. You can avoid bounds checks and special cases by always computing a delta between a newer time and an earlier time. As long as you can guarantee that the sample period is less than the clock rollover period there will never be any ambiguity.
Ada tried imposing the purity of signed integers and had to add modular types to get these semantics because of their utility.
http://www.gotw.ca/publications/c_family_interview.htm
Gosling on why Java only has signed arithmetic.
> At the end of the day, code is for people, so keep it easy for people.
This is a dangerous heuristic, because people here means exclusively developers. It’s easy for us to trade annoying but mostly harmless bugs for rare but harmful ones.
But "unsigned by default" won't save you here; all it does is give you a little more breathing room for your special case code (and hey, maybe that doubled positive integer space is all you needed, in which case congrats).
But all of the other problems are still there. That's why I'm saying that "unsigned by default" is backwards. It should be "signed by default", and unsigned for special situations that warrant it.
A big one is dealing with currencies like Japanese yen in financial software.
The question is: Will the difference between 8 and 16 quintillion matter enough to say "unsigned by default"?
But currency types need to be signed anyway, so I guess that's that ;-)