Stupid little iota of an idea

bearophile bearophileHUGS at lycos.com
Fri Feb 11 12:25:02 PST 2011


Jim:

> bearophile Wrote:
> > Then in D2 for those use an int. Unsigned values are _very_ bug-prone in D2.
> 
> May I ask why?

Because:
- D unsigned numbers are fixed-sized bitfields, they overflow. (Multi-precision values are not built-in, they are currently slow if you need a 30 or 50 or 70 bit long value, and generally they feel like grafted on the language).
- There are no run-time overflow errors, as in C#/Delphi/etc (this is ridiculous for any language that hopes to make safety one of its strong points. Delphi has this feature since ages ago. Not having this in D is like going back to 1980 or before. It gives a peculiar stone-age style to the whole D language).
- D copies the weird/bad C signed-unsigned conversion rules, that cause plenty of troubles.
- D doesn't have warnings like GCC that give a bit of help against the C signed-unsigned conversion rules, nor against things like unsigned<0.

In Delphi using unsigned numbers is safer, but in D it's actually safer to use signed values :-)
All this is compound with the design choice of using signed values for arrays and indexes in D.

One even less bright design decision was to use unsigned longs for array positions, etc:
http://d.puremagic.com/issues/show_bug.cgi?id=5452

Generally in the current D the best advice is to limit the usage of unsigned values as much as possible, and use them only in the uncommon situations where they are needed, like:
- When you need the full range of 8, 16, 32 or 64 bits. This is uncommon, but it happens. Example: you really want to save memory to store indexes and you need you will have no more than about 40_000 items. Then use an ushort.
- To store bitfields, like an array of 50_000 bits, to implement a bit set, some kind of bitmap, bloom filter, etc.
- When you need to deserialize or receive data from some channel or memory, that you know is for example a 32 unsigned int or 16 bit unsigned int, a unsigned 8 bit digital signal from some instrument, etc.

In most other cases it's better to use signed values, for example you will avoid several bugs if in your code you use lines of code like:
int len = array.length;
and then you use len in the rest of your function.

Bye,
bearophile


More information about the Digitalmars-d mailing list