Premature conversion

Lutger lutger.blijdestijn at gmail.com
Wed Nov 7 04:52:21 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/
> 
> Best regards
> 
> Hans-Eric Grönlund
> 

I responded in your blog, but I might as well respond here too to this 
question.

Speaking for myself, I understand the rationale as follows:

1. in assignment, the expression on the right hand side is evaluated and 
then assigned to the left hand side.
2. if the types don't match, the rhs is implicitly converted if that is 
allowed.

In this case, the '/' operator is defined for integral operands, thus 
the result is an integer division which is then converted to a floating 
point type.

This makes it intuitive for me, I would be surprised if the expression 
on the right hand side is evaluated differently depending on the type of 
the left hand side. That would be a gotcha, especially if the expression 
is more complicated.

If floating point and integral division would have different operators 
this reasoning wouldn't apply. But that's another story.






More information about the Digitalmars-d-learn mailing list