isocpp / isocpp/CppCoreGuidelines

Suggest gsl::narrow/gsl::narrow_cast for float/double to integral conversions in ES.46

Open
#1,721 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

One of the things ES.46 touches upon is the following:

Enforcement
A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:

Flag all floating-point to integer conversions (maybe only float->char and double->int. Here be dragons! we need data).

We have recently ran into an issue where directly casting a negative double to an unsigned integral type results in inconsistent code generation when targeting a specific architecture. Therefore, we want to implement a static check that flags all conversions from negative double/float to unsigned integral types and suggests to use gsl::narrow or gsl::narrow_cast. My hope is we can then update the existing implementation of gsl::narrow/gsl::narrow_cast to guard against such conversions by first going from float/double to signed integral type and then convert the result to unsigned, guarding against data loss during the process.

Can we improve the documentation of ES.46 such that it suggests people to use gsl::narrow and gsl::narrow_cast when doing float/double to integral conversions?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in CppCoreGuidelines.md at the ES.46 (Res-narrowing) section and review its enforcement guidance on floating-point to integer conversions. Update the documentation to suggest gsl::narrow and gsl::narrow_cast for these conversions, then verify that the ES.46 wording clearly reflects the requested recommendation.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.