Premature conversion

Bill Baxter dnewsgroup at billbaxter.com
Wed Nov 7 04:13:38 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/

I'm pretty sure the reason it works that way is because that's exactly 
how it works in C (and C++).  So making 5/2 result in 2.5 would be a
"gotcha" for any C programmer expecting D to act more or less like C.

Python has been transitioning from having rules like C to having a 
special integer division operator, //.   So in Python with the new rules 
(or with 'from future import division')   5/2 is 2.5  and 5//2 is 2.

Personally I don't have a problem with either way.

--bb


More information about the Digitalmars-d-learn mailing list