EOF considered harmful

Michael Condict condict at cs.vu.nl
Wed Oct 25 19:35:16 AEST 1989


In article <266 at m1.cs.man.ac.uk> ian at r6.UUCP (Ian Cottam) writes:
| Some observations on the little program below (following some recent
| discussions in this group):
| _______________________
| #include <stdio.h>
| 
| int
| main()
| {
| 	char ch;
| 	while ( ! feof(stdin) ) {
| 		ch= getchar();
| 		putchar(ch);
| 	}
| 
| 	return 0;
| }
| ______________________
| 
| 1) This program runs as quickly as the ``((ch= getchar()) != EOF)''
|    version (on my SUN3 with gcc).
| 
| 2) Although in this specific example the variable ch is redundant, I
|    include it to show that declaring it to be a char is quite sensible
|    given the feof() test.  Thus a common error in C code -- a colleague
|    of mine even found this error in K&R first edition -- the sign extension
|    (or not) character comparison with EOF is avoided.
| 
| 3) The, to my mind, awful idiom in 1) above is avoided, with the extra
|    benefit that the ``(ch= getchar() != EOF)'' slip up will not be made.
| 
| 4) This code is completely portable to implementations that have:
| 		sizeof(char) == sizeof(int)
| 

It is hard to argue any of the above (4) points, either for or against, since
the program is just wrong.  The feof test indicates whether EOF has PREVIOUSLY
been encountered in stdin.  It does not mean that it is safe to read a char.
This program always produces an extra character of output (EOF truncated to
a char) that wasn't in the input.

The program does, however, nicely display another disadvantage of an
eof-testing predicate: it is all too easy for the eof test to be "out of sync"
with the call to the input function.  This happens to beginner Pascal
programmers all the time.  It cannot happen with an in-band EOF value.

Michael Condict		condict at cs.vu.nl
Vrije University
Amsterdam
-- 
Michael Condict		condict at cs.vu.nl
Vrije University
Amsterdam



More information about the Comp.lang.c mailing list