c语言 - 为什么 clang -Wempty-body 没有检测到这种情况?



回答Xcode- c编程后 - 循环时,我停止做出理论答案并在Windows盒上安装了clang,以检查它是否比警告诊断部门中的gcc更好。

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

  • 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);
         ^

while未检测到空的if

现在,我将减少指令包裹在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在警告检测方面显然仍然很出色(另请参见为什么我在这个琐事示例中没有从GCC发出的"使用Unitialized&quot"?)

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

这是为了避免太多的误报。通常,if (expr);永远不会有意义,但是while (expr);不必是错误,因为expr的副作用可能会导致表达式从真实变为false。例如,

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

这是来源解释的方式:

// `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);

相关内容

最新更新