Killing integer division problems?
burt
invalid_email_address at cab.abc
Tue Aug 4 12:34:37 UTC 2020
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);
```
If I don't want to keep that behaviour, then the compiler has
shown me the bug and I can fix it:
```d
y += 1.0 / b;
```
It doesn't silently change behaviour that used to be valid in C
(it will emit a warning) and can be fixed trivially, so it
shouldn't be an intrusive change (and might even catch bugs that
weren't found yet).
Would such a change require a DIP? Could a -preview/-transition
flag be added to warn me about integer divisions? What do you
think?
More information about the Digitalmars-d
mailing list