Using SonarQube 9.3 I stumbled upon this issue in our code base.
static constexpr double someName = 0.435;
This code triggers SonarSource Code Analyzers Rules Explorer Because apparently
0.435 is close enough to
log10(e) that the analyzer thinks that this constant is meant to represent that. But that’s not true.
The utility to find places where we want to start using
std::numbers is useful, but this false positive is annoying. I’m wondering if the check can be made more precise, or if there’s an elegant way to write this without triggering this code smell.
In this case it looks like there are are enough rounding error that this number should probably not be approximated as being
Judging by the calculator in Windows
and the python shell
It seems like
0.434 would have been closer anyway. But maybe the point of using the standard library constants is to achieve higher precession anyway.
Maybe there should be a configuration on the rule that lets us provide some delta value that is used to detect if a hardcoded value is close enough to a mathematical constant.
To add a little background – the analyzer checks for just 13 mathematical constants, and checks if a value is within
0.001 of those constants (up or down).
Do you think it’s really worth adding some extra logic here (or increased precision) – or is it enough to mark this case as a false-positive?
I would say that there is some value, but I don’t know how to balance that versus the overhead of having users consider these cases on a case by case basis.
Maybe something different from plus minus 0.001 would be a good idea as well. My first reaction was in terms of usual rounding rules. Which I guess might be a better idea anyway. Because I guess if you use a delta of 0.001, then if someone is using a constant with fewer digits then one might miss this case. Like, I would have expected
const double pi = 3.14 to be caught by this rule, which I guess it doesn’t if the difference has to be smaller than 0.001.
I think your suggestion makes sense, and I created a ticket to implement it.
However, if your code contained
auto d = 0.434, the issue would be raised, even with your proposed change. I think this is inevitable with this kind of rule, and I suggest you should just mark this as false positive.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.