Xcode- C programming - While loop

感情迁移 提交于 2019-12-10 10:50:00

问题


I have an error/warning associated with "while" loop, in Xcode. Any suggestions on how to fix it?

while ( (c=getchar() != '\n') && c != EOF);

While loop has empty body

Picture in the IDE:


回答1:


Without knowing which compiler is behind it, I can just list the know warning flags for 2 of them:

  • clang -Wempty-body; included in -Wextra too;
  • Visual C++ C4390, included in /W3

(source: Why didn't the compiler warn me about an empty if-statement?)

While this compiler warning is very useful for conditions without side-effects like

while (i > 0);
{
   --i;
}

(which would cause an infinite loop)

in your specific case:

while ( (c=getchar() != '\n') && c != EOF);

is a perfectly idiomatic way of skipping to the next line of stdin or end of input.

From the text of the warning that XCode prints (and which comes from the underlying compiler), I'm pretty sure that your XCode is configured with clang, so, yes, there's a way to turn the warning off when using clang:

$ clang test.c 
test.c:6:12: warning: while loop has empty body [-Wempty-body]
  while (0);
           ^
test.c:6:12: note: put the semicolon on a separate line to silence this warning

in your case:

while ( (c=getchar() != '\n') && c != EOF)
;

in that case (matter of personal taste) I would do:

while ( (c=getchar() != '\n') && c != EOF)
{}

since they are strictly equivalent

So you can leave the warning set for other cases where a semicolon could be typed unwillingly and explicitly tell the compiler not to worry about those cases.



来源:https://stackoverflow.com/questions/46496135/xcode-c-programming-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!