'int' is enough for 'length' to migrate code from x86 to x64

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Wed Nov 19 12:04:15 PST 2014


On 11/19/14 10:09 AM, Ary Borenszweig wrote:
> On 11/19/14, 7:03 AM, Don wrote:
>> On Tuesday, 18 November 2014 at 18:23:52 UTC, Marco Leise wrote:
>  >
>> Weird consequence: using subtraction with an unsigned type is nearly
>> always a bug.
>>
>> I wish D hadn't called unsigned integers 'uint'. They should have been
>> called '__uint' or something. They should look ugly. You need a very,
>> very good reason to use an unsigned type.
>>
>> We have a builtin type that is deadly but seductive.
>>
>
> I agree. An array's length makes sense as an unsigned ("an array can't
> have a negative length, right?") but it leads to the bugs you say. For
> example:
>
> ~~~
> import std.stdio;
>
> void main() {
>    auto a = [1, 2, 3];
>    auto b = [1, 2, 3, 4];
>    if (a.length - b.length > 0) {
>      writeln("Can you spot the bug that easily?");
>    }
> }
> ~~~
>
> Yes, it makes sense, but at the same time it leads to super unintuitive
> math operations being involved.
>
> Rust made the same mistake and now a couple of times I've seen bugs like
> these being reported. Never seen them in Java or .Net though. I wonder
> why...

There are related bugs in Java too, e.g. I remember one in binary search 
where (i + j) / 2 was wrong because of an overflow. Also, Java does have 
a package for unsigned integers so apparently it's necessary.

Andrei



More information about the Digitalmars-d mailing list