为什么clang -wempty-body没有检测到这种情况?

时间:2017-09-30 13:04:37

标签: c clang compiler-warnings

在回答Xcode- C programming - While loop后,我停止提出理论答案并在我的Windows框中安装了clang,以检查它是否真的比警告诊断部门中的gcc好。< / p>

我在-Wempty-body中使用clang来编译此代码,这是错误的,因为:

  • while指令以分号结束,长时间结束后用分号结束可能的拼写错误...:无限循环
  • if语句的相同内容,使测试无效

错误的代码:

int main(void)
{
   char c=1;
   while (c);
   --c;
   if (c);
}

我尝试用clang(5.0.0 x64 windows)编译它:

输出:

S:\c>clang -Wempty-body test.c
test.c:8:10: warning: if statement has empty body [-Wempty-body]
   if (c);
         ^

if isn&f;

时检测到空while

现在我在while之后的一个块中包装递减指令:

int main(void)
{
   char c=1;
   while (c);
   { --c; }
   if (c);
}

现在它似乎正确地检测到了两者:

test.c:6:10: warning: if statement has empty body [-Wempty-body]
   if (c);
test.c:4:13: warning: while loop has empty body [-Wempty-body]
   while (c);

注意:gcc无法看到while个错误,因此clang在警告检测方面仍然明显优越(另请参阅why am I not getting an "used uninitialized" warning from gcc in this trivial example?

这背后的启发式是什么?那是一个错误吗?

1 个答案:

答案 0 :(得分:3)

避免过多的误报。一般来说,if (expr);永远不会有意义,但while (expr);不一定是错误,因为expr的副作用可能会导致表达式从true切换为false。例如,

void processAllElements() {
  while (tryProcessNextElement());
}

以下是the source对其的解释:

// `for(...);' and `while(...);' are popular idioms, so in order to keep
// noise level low, emit diagnostics only if for/while is followed by a
// CompoundStmt, e.g.:
//    for (int i = 0; i < n; i++);
//    {
//      a(i);
//    }
// or if for/while is followed by a statement with more indentation
// than for/while itself:
//    for (int i = 0; i < n; i++);
//      a(i);