Premature conversion

Regan Heath regan at netmail.co.nz
Wed Nov 7 02:37:22 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? 
> 
> There are more details on my weblog:
> http://www.hans-eric.com/2007/11/06/d-gotchas/

You are performing 'integer' division then converting the result to a 
real.  With integer division 5/2 is 2 remainder 1.

This code behaves as you would expect (I suspect):

real a = 5.0/2.0;

Here 5.0 and 2.0 are floating point literals, not integer literals so 
floating point division is performed resulting in 2.5.

These also work as you'd expect:

real a = 5/2.0;
real a = 5.0/2;

because D will promote integer literals to floating point in these cases.

I'm sure there are some rules on the D website for how and when and why 
it promotes integers to floats and so on but I can't find them at present.

Regan




More information about the Digitalmars-d-learn mailing list