问题描述
这直接取自《 K& R》一书:
This is taken directly from the K&R book:
c = getchar() != EOF
等同于
c = (getchar() != EOF)
这具有将c设置为0或1的不良效果,具体取决于getchar的调用是否返回文件末尾. (有关更多信息,请参见第2章.)
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.)
练习1-6.验证表达式getchar() != EOF
是0还是1.
Exercise 1-6. Verify that the expression getchar() != EOF
is 0 or 1.
我在理解如何进行此练习以及理解被加引号的段落中所发生的事情时遇到了麻烦.
I am having trouble understanding how to do this exercise as well as understanding what is going on with the blockquoted paragraph.
我知道EOF是int类型的符号常量,通常保持值-1.由于负值int在进行比较时永远无法拥有与char相同的值,因此需要将其提升为int,然后以某种方式表示文件结束.
I know that EOF is a symbolic constant of type int and usually holds the value -1. Since a negative valued int can never hold the same value as char when it makes a comparison it needs to be promoted to int which then somehow signals the end of file.
我也得到了没有指定括号的情况,比较!=
是在赋值之前完成的,但这实际上是什么意思?该功能会发生什么?我还打印了EOF的值,它是-1,它表示验证为0或1时是什么意思?
I also get that without the parenthesis specified above the comparison !=
is done before the assignment but what does this actually mean? What is it that happens to that function? Also I printed the value of EOF and it was -1 what does the exercise mean when it says verify it is 0 or 1?
推荐答案
是说:
c = (getchar() != EOF)
表示从stdin
中读取一个字符,然后将其与EOF进行比较.如果为true,则结果为1,如果为false,则结果为0.然后将该结果分配给c
.读取的字符丢失,因此具有不良影响".
means read a character from stdin
, then compare it against EOF. The result of this is 1 if true, 0 if false. That result is then assigned to c
. The character that was read is lost, hence 'undesired effect'.
它希望您以这种方式自己运行此命令,以了解如何通过发送EOF与其他任何字符来产生0和1.
It wants you to run this yourself in this way to see how you can produce 0 and 1 by sending EOF vs. any other character.
这篇关于EOF练习1-6 K& R C编程语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!