Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

K&R C Exercise 4-9: Why ignore EOF?

Tags:

c

push-back

Just a little confusion I'm hoping someone can clear up - this question asks: "Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, then implement your design".

With the code as it is, an EOF is pushed back, refetched with getch(), which causes a loop such as:

while ((c = getch()) != EOF)
    putchar(c);

to terminate when it is encountered from the buffer. I fail to see how this behaviour is incorrect. Surely as an EOF will in theory (mostly) only ever be encountered once, if it is pushed back and then read from a buffer in this way, it doesn't really matter? I hope someone could clear up the purpose of this question for me - I get that most solutions involve programming ungetch() to ignore EOF, I just don't see the point.

I'm sure there is one, as Dennis Ritchie and Brian Kernighan are a lot brighter than little old me - just hoping someone could point it out. Thanks :-)

Regards, Phil

like image 810
PhilPotter1987 Avatar asked Sep 15 '13 23:09

PhilPotter1987


1 Answers

The definition of buf is char buf[BUFSIZE]; ,according to the content in the book, page 19:

We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int.

Then we get the answer:

int buf[BUFSIZE];
like image 134
prehistoricpenguin Avatar answered Oct 11 '22 02:10

prehistoricpenguin