A confusing expression?

bearophile bearophileHUGS at lycos.com
Sun Aug 1 16:22:42 PDT 2010


Time ago an automatic tool has said that in a line of C code similar to:
int r = x / y * z;

a division operator followed by a mult is confusing, and to add parentheses to improve the code:
int r = (x / y) * z;


When values are integral the position of parentheses can change the value of the expression:

void main() {
    int x = 10;
    int y = 3;
    int z = 5;
    assert(x / y * z == 15);
    assert((x / y) * z == 15);
    assert(x / (y * z) == 0);
}


Turning 'x / y * z' into a D syntax error (as done in bug  http://d.puremagic.com/issues/show_bug.cgi?id=4077 ) looks excessive to me. A warning seems enough, but Walter is not a lover of warnings (and sometimes I agree, I'd like to turn three D warnings into errors). What do you think?

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list