Killing integer division problems?

bachmeier no at spam.net
Tue Aug 4 15:25:50 UTC 2020

```On Tuesday, 4 August 2020 at 12:34:37 UTC, burt wrote:
> Hello,
>
> A while ago I spent an hour figuring out why some variable
> wasn't changing like it should, and the reason was something
> like the following (although in a much more complex expression):
>
> ```d
> double y = 0.0;
> // ...
> y += 1 / b; // with b : int
> // ...
> ```
>
> I have run into this C remnant multiple times now and spent
> much too long trying to find out what happened, so to fix it,
> here's my proposal:
>
> "Make integer division without cast illegal."
>
> In the case above, the compiler would complain (or at least
> emit a warning) that there is integer division going on and
> that the result will be truncated.
>
> If I want to keep the integer division behaviour, I would just
> have to change the code to:
>
> ```d
> y += cast(int) (1 / b);
> ```

This would be *really* confusing. y is a double in your example,
and the user would be forced to cast to an int in order to enable
an implicit cast (or promotion, or whatever language you want to
use) to a double?

I hate the current default behavior. It's not safe but it is
consistent with what a C programmer will expect. You can't have
these yielding different values:

```
x = 7/3;
y = 7/3;
```

If x is an int and y is a double, you'd get different results,
and that would be awful. What's needed is something explicit like
this:

y = double(7/3);
x = 7/3;
y = 7/3; // Error because of implicit cast

There is precedent for this in the change to foreach. This code

import std;
void main()
{
foreach(int ii, val; [1.1, 2.2, 3.3]) {
writeln(ii);
writeln(val);
}
}

returns

onlineapp.d(4): Deprecation: foreach: loop index implicitly
converted from size_t to int
0
1.1
1
2.2
2
3.3

You have to do the casting inside the loop instead.
```