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:
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:
Without knowing which compiler is behind it, I can just list the know warning flags for 2 of them:
-Wempty-body
; included in -Wextra
too;/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.