Home > front end >  How to get clang to warn about very simple narrowing
How to get clang to warn about very simple narrowing

Time:10-13

If I am using clang tools, what is the recommended way to get clang or some part of the clang toolchain to tell me that e.g. passing an int to a function that takes a short might be a bad idea?
Given this very simple program

static short sus = 0;
void foo(short us) {
  sus = us;
}

int main() {
  int i = 500000;
  foo(i);   // any indication from clang this might be a bad idea
  return 0;
}
  • I've tried -Wall and -Wextra,
  • I've tried clang-tidy with cppcoreguidelines-narrowing-conversions
  • I've tried clang -analyze

I must be missing something very simple here, right?

CodePudding user response:

The -Weverything option is useful in situations like this. It enables every warning option that clang has, including many that -Wall -Wextra doesn't include. Many of them are useless or counterproductive, but if there is one that warns on the code you consider problematic, this will let you find it, and tell you which option would enable it specifically. Try it on godbolt.

In this case, using -Weverything shows us:

<source>:8:7: warning: implicit conversion loses integer precision: 'int' to 'short' [-Wimplicit-int-conversion]
  foo(i);   // any indication from clang this might be a bad idea
  ~~~ ^

So the option you want is -Wimplicit-int-conversion.

  • Related