bearophile can say "i told you so" (re uint->int implicit conv)

Don turnyourkidsintocash at nospam.com
Tue Apr 2 02:40:34 PDT 2013


On Tuesday, 2 April 2013 at 08:29:41 UTC, renoX wrote:
> On Tuesday, 2 April 2013 at 07:49:04 UTC, Don wrote:
> [cut]
>> IMHO, array.length is *the* place where unsigned does *not* 
>> work. size_t should be an integer. We're not supporting 16 bit 
>> systems, and the few cases where a size_t value can 
>> potentially exceed int.max could be disallowed.
>>
>> The problem with unsigned is that it gets used as "positive 
>> integer", which it is not. I think it was a big mistake that D 
>> turned C's  "unsigned long" into "ulong", thereby making it 
>> look more attractive. Nobody should be using unsigned types 
>> unless they have a really good reason. Unfortunately, size_t 
>> forces you to use them.
>
> You forgot something: an explanation why you feel that way..
> I do consider unsigned int as "positive integer", why do you 
> think that isn't the case?

You can actually see it from the name. An unsigned number is 
exactly that -- it's a value with *no sign*. That's quite 
different from a positive integer, which is a number where the 
sign is known to be positive.

If it has no sign, that means that the interpretation of the sign 
requires further information. For example, it may be the low 
digits of a multi-byte number. (In fact, in the Intel docs, 
multi-word operations are the primary reason for the existence of 
unsigned operations). It might also be a bag of bits.

Mathematically, a positive integer is Z+, just with a limited 
range. If an operation exceeds the range, it's really an overflow 
error, the representation has broken down.

An uint, however, is a value mod 2^^32, and follows completely 
normal modular arithmetic rules. It's the responsibility of the 
surrounding code to add meaning to it.

But very often, people use 'uint' when they really want an int, 
whose sign bit is zero.

> IMHO the issue with unsigned are
> 1) implicit conversion: a C mistake and an even worst mistake 
> to copy it from C knowing that this will lead to many errors!
> 2) lack of overflow checks by default.

I'm not sure how (2) is relevant.
Note that overflow of unsigned operations is impossible. Only 
signed numbers can overflow. Unsigned numbers wrap instead, and 
this is not an error, it's the central feature of their semantics.


More information about the Digitalmars-d mailing list