logoalt Hacker News

einpoklumyesterday at 7:33 PM1 replyview on HN

It's not "can't be negative", it's just that the semantics for negativity is wrapping around.

And - yes, there are very important use cases for unsigned/modulo-2n/wraparound values. But sizes of data structures are generally _not_ one of those use cases. The fact that the size is non-negative does not mean that the type should be unsigned. You should still be able to, say, subtract sizes and get a signed value which may be negative.


Replies

throwaway894345yesterday at 8:03 PM

That’s definitely not true. Unsigned ints have no “negativity” semantic. Wrapping around is what happens when you decrement the minimum value of any integer type, including signed types. Regardless of the type you use to represent an integer value that cannot legally be negative, you will have to take care not to allow your program to return values lower than zero for things like indices or sizes.

show 2 replies