2

I'm getting a clang-tidy warning that reads narrowing conversion from 'int' to 'float' when I convert from a uint8_t to a float, which to my understanding is not a narrowing conversion since float can represent every integer that a uint8_t can.

Code example:

uint8_t testVar = 8;
float test2 = 2.0f * testVar;

clang-tidy flags the second line of that with the warning cppcoreguidelines-narrowing-conversions: narrowing conversion from 'int' to 'float'. In my IDE, the squiggle shows up under the testVar.

According to the reference, this warning should be flagged if we convert from an integer to a narrower floating-point (e.g. uint64_t to float), but to the best of my knowledge, float is not narrower than uint8_t.

Am I fundamentally misunderstanding these data types, or is something else going on here?

I'm on LLVM version 11.0.0 if that matters.

5
  • 3
    I think the problem is that the uint8_t is implicitly converted to unsigned before it is then converted to float. Obviously clang-tidy is not being very smart. Commented Dec 25, 2020 at 21:19
  • @john Correct me if I'm wrong, but I thought the u already stood for unsigned. My IDE tells me that uint8_t is just an alias for unsigned char. Commented Dec 25, 2020 at 21:21
  • 3
    Yes but the rules of C++ say that when you use a uint8_t in an expression it is implicitly converted to unsigned int. This is called integer promotion Commented Dec 25, 2020 at 21:22
  • Clearly clang-tidy is not going deep enough. Here are two points which might be misleading it. 1. float is signed which is always smaller than the range of unsigned types. 2. float covers smaller range than int. Although uint8_t ultimately boils down to something equivalent of unsigned char but as stated before, clang-tidy is not going that deep. Commented Dec 25, 2020 at 21:44
  • Just out of curiosity - is this warning generated when you actually run clang-tidy, or is it just a squiggle in your IDE's text editor? If the latter, then it may be that the "IntelliSense" feature of your IDE isn't properly using clang-tidy. Using the clang static analyser in VS-2019, I don't get that warning. Commented Dec 26, 2020 at 1:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.