View mode: basic / threaded / horizontal-split · Log in · Help
January 21, 2010
"Unsigned-related bugs never occur in real code."
"It's an academic problem. Don't worry about it and move on."

That's what Walter kept on telling me. Yet I've spent the better part of 
an hour reducing a bug down to the following:

import std.math, std.stdio;

void main() {
    auto a = [ 4, 4, 2, 3, 2 ];
    float avgdist = 0;
    uint count;

    foreach (i, e1; a) {
        foreach (j, e2; a) {
            if (i == j) continue;
            if (e1 != e2) continue;
            ++count;
            avgdist += abs(i - j);
        }
    }

    writeln(count, " ", avgdist / count);
}

May this post be an innocent victim of the war against unsigned-related 
bugs.


Andrei
January 21, 2010
Re: "Unsigned-related bugs never occur in real code."
Andrei Alexandrescu:
>May this post be an innocent victim of the war against unsigned-related bugs.<

Unsigned numbers are evil (especially if you use them in a language with no integral overflow tests).

A partial solution to this problem is:
1) to use them in a program only where you really need them, for example as bitfields or as an optimization, etc (this can be done in D1 too);
2) to have compile-time & run-time integral overflow tests active by default unless they are disabled with a compiler command line argument, as in Delphi, C#, etc (this can be done in D1 too);
4) to use more unit tests, every little piece of code you write has to be tested. And adding invariants along the way in your computations is positive (this can be done in D1 too);
3) to replace size_t with ptrdiff_t everywhere in the language and standard library, unless really needed (so those i and j are signed integers by default, array.length returns a signed value, array slicing and indexes have a signed value argument, etc) (I think this can't be done in D1).

Doing those three things is not going to solve the problem fully, but it will reduce the bug count in D programs. (Once that's done I'd like to see how many bugs it catches in the std lib, and other libs & programs already written). A better solution is the one I've explained in the comments about Guy Steele. Fixed-sized numbers (even with overflow tests) are necessary for performance and I want them available where I need more performance, to me but they look more and more like a premature optimization.

Bye,
bearophile
Top | Discussion index | About this forum | D home