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.
Thanks for taking the time to share this suggestion. This item has been around for a couple of versions of Visual Studio and we haven’t acted on it. Looking at the VS “15” plans, we’re not going to take action on this item, so we’re going to close it. If the suggestion is still relevant, please either take a look to see if there’s another suggestion that’s similar that you can vote on, or open a new suggestion.
- The Visual Studio Team