Detecting inadvertent use of integer division

Don nospam at nospam.com
Tue Dec 15 00:02:01 PST 2009


Phil Deets wrote:
> On Mon, 14 Dec 2009 04:57:26 -0500, Don <nospam at nospam.com> wrote:
> 
>> In the very rare cases where the result of an integer division was 
>> actually intended to be stored in a float, an explicit cast would be 
>> required. So you'd write:
>> double y = cast(int)(1/x);
> 
> To me,
> 
> double y = cast(double)(1/x);
> 
> makes more sense. Why cast to int?

That'd compile, too. But, it's pretty confusing to the reader, because 
that code will only set y == -1.0, +1.0, +0.0, -0.0, or else create a 
divide by zero error. So I'd recommend a cast to int.





More information about the Digitalmars-d mailing list