以下内容直接摘自 K&R 书籍:
我不太理解如何完成这个练习以及块引用段落中发生的事情。The precedence of
!=
is higher than that of=
, which means that in the absence of parentheses the relational test!=
would be done before the assignment=
. So the statementc = getchar() != EOF
is equivalent to
c = (getchar() != EOF)
This has the undesired effect of setting c to 0 or 1, depending on whether or not the call of getchar returned end of file. (More on this in Chapter 2.)
Exercise 1-6. Verify that the expression
getchar() != EOF
is 0 or 1.
我知道 EOF 是 int 类型的符号常量,通常值为 -1。由于负值的 int 无法与 char 相同的值进行比较,所以它需要被提升为 int,然后以某种方式表示文件的结尾。
我也明白,在上面未指定括号的情况下,赋值操作会在比较操作 '!=' 之前执行,但实际上意味着什么?那个函数会发生什么事情呢?此外,我打印了 EOF 的值是 -1,当练习说要验证它是否为 0 或 1 时,这意味着什么?
(getchar() != EOF)
的值是0还是1。括号中的句子意味着如果没有括号,它与c = (getchar() != EOF)
相同。 - Daniel Fischergetchar
的结果存储在一个char
中,那么当检查是否等于EOF
时,它的实现是不确定的。如果char
是有符号的,那么可能没问题 -- 但它会错误地将值为 255 的字符解释为 EOF,这不是好的编程习惯。 - teppic