I suggest you ...

Add a warning when promoting the result of integer division to a real

(Also applies to C++)

I find a very common source of annoying and sometimes difficult bugs is forgetting that integer division truncates the fractional component even when the result is being promoted to a real. As a simplistic example:

int a = 5;
double b = a / 2;

Mathematically one expects b=2.5 but in fact this will result in b=2.0. Of course, one can correct this by instead simply using:

double b = a / 2.0;

However, I wish I had a dollar for every time I forgot to do this.

It would be really nice if this general scenario caused a warning, as the result will probably not be what the programmer intended.

Of course, more complex expressions may result in the promotion not occurring until after the evaluation of one or more other operators, so there would be a bit of work for the compiler, but it should not be too hard. The expression evaluation would just have to propagate a flag indicating whether an r-value relies upon such a division, and when an r-value bearing this flag goes into a promotion to a real, issue the warning.

Thanks for considering this.

Kevin

4 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Kevin MKevin M shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    1 comment

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...

      Feedback and Knowledge Base