What's C's biggest mistake?

bearophile bearophileHUGS at lycos.com
Wed Dec 30 12:19:24 PST 2009


Bane:
>Now that its done, I can newer go back typing & ** -> #ifdef... when I can accomplish same thing with much less headache using D.<

The # symbol is essentially forbidden in D, because of C compatibility... -.-

The replacement of -> with the dot is cute and handy, but it leads to a little break of symmetry still. If you have a class like:

class V3 {
    float[3] data;

    void opIndexAssign(float x, size_t i) {
        data[i] = x;
    }

    double dot() {
        float s = 0.0; // slow
        foreach (d; data)
            s += d * d;
        return s;
    }
}

void main() {
    V3 v = new V3;
    v[0] = 1.0;
    v[1] = 2.0;
    v[2] = 3.0;
    printf("%f\n", v.dot());
}


To increase performance you may want to rewrite it as:

struct V3 {
    float[3] data;

    void opIndexAssign(float x, size_t i) {
        data[i] = x;
    }

    double dot() {
        float s = 0.0; // slow
        foreach (d; data)
            s += d * d;
        return s;
    }
}

void main() {
    V3* v = new V3;
    (*v)[0] = 1.0;
    (*v)[1] = 2.0;
    (*v)[2] = 3.0;
    printf("%f\n", v.dot());
}
  
As you see the call to the dot() is unchanged, while the usage of opIndexAssign() is changed.
The last line can also be written like this:
printf("%f\n", (*v).dot());


To restore symmetry you can also write this, but I am not sure if this is good practice:

struct V3 {
    float[3] data;

    void opIndexAssign(float x, size_t i) {
        data[i] = x;
    }

    double dot() {
        float s = 0.0; // slow
        foreach (d; data)
            s += d * d;
        return s;
    }
}

struct V3p {
    V3* ptr;

    void opIndexAssign(float x, size_t i) {
        assert(ptr != null);
        (*ptr)[i] = x;
    }

    double dot() {
        assert(ptr != null);
        return ptr.dot();
    }
}

void main() {
    V3p v = V3p(new V3);
    v[0] = 1.0;
    v[1] = 2.0;
    v[2] = 3.0;
    printf("%f\n", v.dot());
}

Bye,
bearophile



More information about the Digitalmars-d mailing list