Killing integer division problems?

bachmeier no at
Tue Aug 4 18:11:23 UTC 2020

On Tuesday, 4 August 2020 at 15:43:19 UTC, burt wrote:
> On Tuesday, 4 August 2020 at 15:25:50 UTC, bachmeier wrote:

> That is not what I was proposing (please reread). I am just 
> saying that the bottom one (assuming x is int and y is double) 
> should issue a warning, unless it is explicitly told that 
> integer division is intended.

It may not have been clear from my reply, but I was only saying 
whatever is done, if anything, it has to preserve the constraint 
that the same division return the same result. That part wasn't a 
direct response to your proposal.

>> 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
> This is the same as what I was proposing, except for the syntax 
> to explicitly annotate integer division: in your example, you 
> use a cast to double (to show you're casting from integer to 
> division), in my example, you use a cast to int (to show you're 
> truncating). Open for discussion, but the same idea.

It's kind of the same. There are two issues. One is the integer 
division that is missed. The other is the silent 
casting/promotion of an integer to a double. My opinion is that 
it's rarely the case that this code does what you want:

double y = 7/3;

I just don't think that's reasonable. If you do want integer 
division *and* you want to store it in a double, you should do 
something like

double y = trunc(7.0/3);


int x = 7/3;
double y = x;

I see I had an error above. This

y = double(7/3);

should have been

y = double(7)/3;

The former is not clear, while the latter forces the result to be 
a double. Your proposal of

y += cast(int) (1 / b);

does tell the viewer there's something going on, but the code is 
still not doing what you want. OCaml has its own operator and 
requires all integers to be explicitly promoted to float prior to 
doing the division. That might be overkill, but I prefer it to 
D's current bug-inducing behavior.

More information about the Digitalmars-d mailing list