Premature conversion

Steven Schveighoffer schveiguy at yahoo.com
Wed Nov 7 07:06:50 PST 2007


"Hans-Eric Grönlund" wrote
> The code below:
>
> real a = 5/2;
>
> results in the, to me, unexpected value of 2 for the variable a. What's 
> the rationale behind this behavior?
>

What if you *wanted* to do integer division, and then assign to a real?

I look at this problem EXACTLY like operator precendence.  For example, what 
does x become in the following equation?

int x = 1 + 2 * 3;

If you evaluate (1+2) first, then the result is 9.  If you evaluate (2*3) 
first, the result is 7.  So why isn't it 9?  Because the rules state that 
you do multiplication first.

Back to your example, the compiler has rules, which you must observe to get 
what you want.  The compiler doesn't know what you are thinking, so in 
ambiguous cases you must tell it what you want if what you want is not the 
default.  In D, the rule is to evaluate the rhs first, then promote if 
necessary during assignment.  In this case, (as you note on your blog):

real a = 5.0/2;

This tells the compiler you want to do the conversion to floating point 
BEFORE the operation.
In the case of wanting 1+2 evaluated first:

int x = (1 + 2) * 3;

So complaining that your statement results in 2, and not 2.5 is like 
complaining that the compiler didn't know you wanted to do addition before 
multiplication.

You may now ask, why isn't the default the other way around?  Well, I can't 
really answer that question :)  But I hope the behavior doesn't change 
because I'm sure it would break a lot of code that expects to do integer 
division.

-Steve 




More information about the Digitalmars-d-learn mailing list