Killing integer division problems?

burt invalid_email_address at
Tue Aug 4 13:01:02 UTC 2020

On Tuesday, 4 August 2020 at 12:53:24 UTC, jmh530 wrote:
> On Tuesday, 4 August 2020 at 12:34:37 UTC, burt wrote:
>> [snip]
>> Would such a change require a DIP? Could a 
>> -preview/-transition flag be added to warn me about integer 
>> divisions? What do you think?
> The problem is you have stuff like
> ```d
> int x = 2;
> int y = 4 / x;
> ```
> and now you would be force someone to write a cast.

I guess I should have been more specific, I meant only when 
converting to `double`/`float`/`real`, because then you will 
implicitly lose precision. When converting the result to `int`s, 
you already expect the loss in precision of the division, so it's 
not a big deal.

> That's a big enough change that it would require a DIP. Though 
> I've been hit by the same thing in the past, I would be a bit 
> skeptical you could get it through since a lot of code depends 
> on that.

Perhaps an opt-in flag (-vintdiv or something, just like 
-vtemplates/-vgc) would be more appropriate. It would be a useful 
tool, and I would have it active all the time.

> You could also always use something like below instead of the 
> operator overloading.
> double divide(T, U)(T x, U y)
>     if (isIntegral!T && isIntegral!U)
> {
>     return cast(double) / cast(double) y;
> }

The problem isn't fixing the problem, it's finding it. I would 
have to replace all my divisions with this function, and that's 
not very practical.

More information about the Digitalmars-d mailing list