Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get clang to warn about very simple narrowing

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?

like image 903
Chip Grandits Avatar asked Mar 01 '23 10:03

Chip Grandits


1 Answers

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.

like image 106
Nate Eldredge Avatar answered Mar 05 '23 18:03

Nate Eldredge