TO C OR NOT TO *C

Dave Jones djones at megatest.UUCP
Wed Oct 18 07:24:33 AEST 1989


>From article <1989Oct16.172249.18387 at utzoo.uucp>, by henry at utzoo.uucp (Henry Spencer):
> In article <16107 at nswitgould.cs.uts.oz> jon_hogan-doran%713.600 at fidogate.fido.oz (Jon Hogan-doran) writes:
>>... it said (something like this) that getc(fd)
>>returned an int value .. and yet later on he gave an example
>>(something like this):
>> 
>>char ch;
>>ch=getc(ttyd);
> 
> Barring unusual situations, his example is simply wrong.  getc does return
> an int.  The value will fit in a char except in one important case:  EOF.
> Unless you have reason to be *absolutely certain* that end-of-file will
> not occur when attempting to read that character, the result of getc should
> *never* be assigned to a char without first testing to see if it is equal
> to EOF.  That usually means assigning it to an int first, so you can test
> the value and then use it.

You should use int rather than char, but the EOF business will not
automatically screw up the program. It's implementation dependent.
The following will work fine on Sun's, etc., assuming only that the
input stream consists entirely of printable characters:

#include <stdio.h>

main()
{
  char ch;
  while((ch=getc(stdin))!= EOF)
    fputc(ch, stdout);
}

The reason this works is that on the Sun, chars are signed, printable
characters have positive values, and EOF is negative. But you still
should use int, if only to be morally correct.



More information about the Comp.lang.c mailing list