Skip to content

Fix #12921 New check: Detect floating-point casts that cause loss of precision#6583

Merged
chrchr-github merged 9 commits into
cppcheck-opensource:mainfrom
chrchr-github:chr_12921
Jul 17, 2024
Merged

Fix #12921 New check: Detect floating-point casts that cause loss of precision#6583
chrchr-github merged 9 commits into
cppcheck-opensource:mainfrom
chrchr-github:chr_12921

Conversation

@chrchr-github
Copy link
Copy Markdown
Collaborator

No description provided.

@sonarqubecloud
Copy link
Copy Markdown

@chrchr-github chrchr-github marked this pull request as ready for review July 10, 2024 12:38
@chrchr-github chrchr-github reopened this Jul 10, 2024
@firewave
Copy link
Copy Markdown
Collaborator

There should be existing compiler warnings for this (which we obviously have disabled because they are considered false positives or useless or whatever reason was given).

@chrchr-github
Copy link
Copy Markdown
Collaborator Author

At least clang-tidy and MSVC don't detect this. I have run the new check on a large-ish code base and found more than 30 instances already, no FPs.

@firewave
Copy link
Copy Markdown
Collaborator

double f(double a, double b, float c) {
    return a + (float)b + c;
}
<source>:2:27: warning: implicit conversion increases floating-point precision: 'float' to 'double' [-Wdouble-promotion]
    2 |     return a + (float)b + c;
      |                         ~ ^
<source>:2:16: warning: implicit conversion increases floating-point precision: 'float' to 'double' [-Wdouble-promotion]
    2 |     return a + (float)b + c;
      |              ~ ^~~~~~~~

https://godbolt.org/z/edfMs737P

Also see discussion in #4820 as to way the warning is not enabled in our code base yet.

@chrchr-github
Copy link
Copy Markdown
Collaborator Author

I see, didn't know about that compiler warning. However, -Wdouble-promotion is warning about the up-conversion (twice in your example), not about the loss of precision due to the cast. So it is more noisy than the proposed check.

@firewave
Copy link
Copy Markdown
Collaborator

See also llvm/llvm-project#93288.

@chrchr-github chrchr-github merged commit ed2cd7a into cppcheck-opensource:main Jul 17, 2024
@chrchr-github chrchr-github deleted the chr_12921 branch July 17, 2024 09:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants