EOF considered harmful
Ian Cottam
ian at r6.uucp
Mon Oct 23 01:44:55 AEST 1989
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)
5) Although, to my mind, the above is a compelling argument to abandon the
explicit test for EOF, everyone reading this newsgroup (except me of
course :-) ) will ignore it!
-----------------------------------------------------------------
Ian Cottam, Room IT101, Department of Computer Science,
University of Manchester, Oxford Road, Manchester, M13 9PL, U.K.
Tel: (+44) 61-275 6157 FAX: (+44) 61-275-6280
Internet: ian%cs.man.ac.uk at nss.cs.ucl.ac.uk
JANET: ian at uk.ac.man.cs UUCP: ..!mcvax!ukc!man.cs!ian
-----------------------------------------------------------------
-----------------------------------------------------------------
Ian Cottam, Room IT101, Department of Computer Science,
University of Manchester, Oxford Road, Manchester, M13 9PL, U.K.
Tel: (+44) 61-275 6157 FAX: (+44) 61-275-6280
Internet: ian%cs.man.ac.uk at nss.cs.ucl.ac.uk
JANET: ian at uk.ac.man.cs UUCP: ..!mcvax!ukc!man.cs!ian
-----------------------------------------------------------------
More information about the Comp.lang.c
mailing list