Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top