EOF exercise 1-6 K&R The C programming language

假装没事ソ 提交于 2019-12-19 04:06:02

问题


This is taken directly from the K&R book:

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 statement

c = 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.

I am having trouble understanding how to do this exercise as well as understanding what is going on with the blockquoted paragraph.

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.

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?


回答1:


It's saying that:

c = (getchar() != EOF)

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'.

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.



来源:https://stackoverflow.com/questions/15796758/eof-exercise-1-6-kr-the-c-programming-language

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