Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!snorkelwacker!bloom-beacon!eru!luth!sunic!mcsun!hp4nl!star.cs.vu.nl!condict From: condict@cs.vu.nl (Michael Condict) Newsgroups: comp.lang.c Subject: Re: EOF considered harmful Message-ID: <3807@condict.cs.vu.nl> Date: 25 Oct 89 09:35:16 GMT References: <266@m1.cs.man.ac.uk> Reply-To: condict@cs.vu.nl (Michael Condict) Organization: VU Informatica, Amsterdam Lines: 53 In article <266@m1.cs.man.ac.uk> ian@r6.UUCP (Ian Cottam) writes: | Some observations on the little program below (following some recent | discussions in this group): | _______________________ | #include | | 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@cs.vu.nl Vrije University Amsterdam -- Michael Condict condict@cs.vu.nl Vrije University Amsterdam