logoalt Hacker News

jonstewartyesterday at 7:25 PM2 repliesview on HN

I hate using languages that only have signed integers. Using integers that can’t be negative fits many problems nicely and avoids the edge case of having to check for negative.


Replies

adrian_byesterday at 8:34 PM

You are perfectly right, but neither C nor C++ nor many more recent languages derived from them have non-negative integers.

The so-called "unsigned" integers of C are integer residues, where each value can be interpreted either as both positive and negative or as neither positive nor negative. In any case no "unsigned" value can be said to be non-negative.

You have to go back to languages not contaminated by C, like Ada, to find true non-negative integers among the primitive data types.

In C++, it is possible to define a non-negative integer type, which can have good performance if you implement its operations in assembly language.

However I am not aware of an open-source library including such a type.

show 1 reply
einpoklumyesterday at 7:33 PM

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.

show 1 reply