在回答Xcode- C programming - While loop后,我停止提出理论答案并在我的Windows框中安装了clang
,以检查它是否真的比警告诊断部门中的gcc
好。< / p>
我在-Wempty-body
中使用clang
来编译此代码,这是错误的,因为:
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?)
这背后的启发式是什么?那是一个错误吗?
答案 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);