如何让 clang 发出关于非常简单的缩小的警告

Chi*_*its 6 c++ compiler-warnings narrowing clang++

如果我使用 clang 工具,建议使用 clang 或 clang 工具链的某些部分来告诉我,例如将 an 传递int给需要 a 的函数short可能是一个坏主意?
鉴于这个非常简单的程序

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;
}
Run Code Online (Sandbox Code Playgroud)
  • 我尝试过 -Wall 和 -Wextra,
  • 我尝试过使用 cppcoreguidelines-narrowing-conversions 进行 clang-tidy
  • 我尝试过 clang -analyze

我一定错过了一些非常简单的东西,对吧?

Nat*_*dge 11

-Weverything选项在这种情况下很有用。它启用 clang 具有的每个警告选项,包括许多-Wall -Wextra不包含的警告选项。其中许多是无用的或适得其反的,但如果有一个警告您认为有问题的代码,这会让您找到它,并告诉您哪个选项将专门启用它。 在 godbolt 上尝试一下

在这种情况下,使用-Weverything向我们展示:

<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
  ~~~ ^
Run Code Online (Sandbox Code Playgroud)

所以你想要的选项是-Wimplicit-int-conversion.