0

我正在阅读 Clovis L. Tondo 和 Scott E. Gimpel 的 C 答案书,以了解他们如何编写解决此问题的解决方案。
这是它在那本书中的显示方式:

#include <stdio.h>
main() 
{
  int c;

  while (c = getchar() != EOF) /* <-- This test results in compilation errors */
    printf("%d\n", c);
  printf("%d - at EOF\n", c);
}

将上述代码保存到文件中时编译错误,ex1.6.c如下所示:

bash-3.2$ clang -Wall ex1.6.c
ex1.6.c:2:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^
ex1.6.c:6:12: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
  while (c = getchar() != EOF)
         ~~^~~~~~~~~~~~~~~~~~
ex1.6.c:6:12: note: place parentheses around the assignment to silence this warning
  while (c = getchar() != EOF)
           ^
         (                   )
ex1.6.c:6:12: note: use '==' to turn this assignment into an equality comparison
  while (c = getchar() != EOF)
           ^
           ==
2 warnings generated.

因此,看起来 C 答案书中的解决方案是错误的。我对吗?

这是我尝试的解决方案:

#include <stdio.h>

int main() {
        int c;
        printf( "%d\n",( getchar() != EOF));
        return 0;
}
4

1 回答 1

0

这是一个警告,而不是一个错误。但是警告是正确的,因为您几乎从不希望在诸如ifor之类的布尔上下文中出现这种行为whilec = getchar() != EOF被解析为c = (getchar() != EOF)因为=优先级低于!=,因此c将具有值 0 或 1,具体取决于getchar()返回的值,这是您所期望的

大多数时候人们希望它返回读取的字符,因此必须在=表达式周围加上括号以强制首先完成分配

while ((c = getchar()) != EOF)
于 2021-08-08T05:08:04.437 回答