A confusing expression?

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 2 05:17:48 PDT 2010


On Sun, 01 Aug 2010 19:22:42 -0400, bearophile <bearophileHUGS at lycos.com>  
wrote:

> 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);
> }

That has nothing to do with integral arguments.  That has to do with  
precedence.

assert(x / y * z == (x / y) * z);

is going to pass no matter what the value/type of x, y, z.

And given the values you have for x y z, the following statement is also  
true regardless of type:

assert(x / y * z != x / (y * z));

> 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?

No warning, no error.  It's natural to assume that operations are  
performed from left to right.  I don't find it confusing at all.

-Steve


More information about the Digitalmars-d-learn mailing list