Killing integer division problems?

WebFreak001 d.forum at webfreak.org
Tue Aug 4 12:54:42 UTC 2020


On Tuesday, 4 August 2020 at 12:34:37 UTC, burt wrote:
> [...]
> 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.
>
> [...]

I agree having this as warning would be useful, however it should 
not apply to:

int x = y / z;

but only to

float x = y / z; (and double)

In my mind I would like if this was implemented something along 
the lines "if this expression has an integer division in it and 
is implicitly converted to float/double, emit a warning", if it 
isn't implicitly converted to float/double it should not emit a 
warning, as casts are quite ugly and may introduce bugs later on 
if types change.

Also alternative to casting, which would be safer:

float x = int(y / z);

This is already valid syntax and is basically just like an 
implicit assignment, just explicitly written out. This way you 
can't accidentally change y or z to float/double without 
triggering a compiler error.

The rule with this would be: an implicit conversion to int is 
treated as clearing any integer division flag inside an 
expression.


Though I haven't really contributed to dmd, so I don't know how 
feasible this actually is :)


More information about the Digitalmars-d mailing list